数组进栈求最小字典序

leetcode6202. 使用机器人打印字典许最小的字符串

  1. s中只包含小写字母,可以从小到大枚举字母
  2. 如果要将当前字母全部输出,则肯定需要先将s中包含的字母先操作的t中,所以先预处理s中每个字母最后出现的位置
class Solution {
public:
    string robotWithString(string s) {
        int n = s.size();
        string res, t;
        unordered_map<char, int> cim;
        //预处理每个字母出现的最后的位置
        for(int i = 0; i < n; i ++)
            cim[s[i]] = i;
        int k = 0;
        for(int i = 0; i < 26; i ++) {
            char c = i + 'a'; //当前枚举到到字母为c
            if(cim.count(c) == 0) continue;
           // 要先处理t,如果t不为空并且t的末尾有小于等于c的字母,将其弹出并写入结果字符串
            while(t.size() && t.back() <= c) { 
                res += t.back();
                t.pop_back();
            }
           // 然后处理s,将当前字母最后一个位置之前的都操作到t
           // 如果是c,可以直接接入结果字符串;不是c,则接入t
            while(k <= cim[c]) {
                if(s[k] == c) res += c;
                else t += s[k];
                k ++;
            }
        }
       //循环结束,s中所有的字母都已被操作
       //所以将t中的字母接入res
        reverse(t.begin(), t.end());
        return res + t;
    }
};
posted @ 2022-10-09 14:37  jujubos  阅读(36)  评论(0)    收藏  举报