天天看點

【Daily Practice】316. 去除重複字母

leetcode 316題

了解思路,暫不能保證AC;

class Solution {
public:
    string removeDuplicateLetters(string s) {
        stack<char> st;

        int *countArr = new int[256]{0};
        for (int i = 0; i < s.size(); i++) {
            countArr[s[i]]++;
        }

        bool inStack[256] = false;
        for (char c : s) {
            countArr[c]--;

            if (inStack[c]) {
                continue;
            }

            while (!st.empty() && st.top() > c) {
                if (countArr[st.top()] == 0) {
                    break;
                }
                inStack[st.top()] = false;
                st.pop();
            }
            st.push(c);
            inStack[c] = true;
        }

        string res = "";
        while (!st.empty()) {
            res += st.top();
            st.pop();
        }
        reverse(res.begin(), res.end());
        return res;
    }
};

           

繼續閱讀