力扣2434.使用机器人打印字典序最小的字符串
枚举所有字母入栈 用数组记录每个字母出现次数
- 同时维护剩余字母中最小值
- 判断当前栈顶字母和剩余字母中最小值哪个更小
- 始终找最小的加入答案
class Solution { public: string robotWithString(string s) { string ans; int cnt[26],min=0; for(char c:s) cnt[c - 'a'] ++; stack<int> st; for(char c:s) { cnt[c - 'a'] --; while(min < 25 && cnt[min] == 0) min ++; st.push(c); while(!st.empty() && st.top() - 'a' <= min) { ans += st.top(); st.pop(); } } return ans; } };