【leetcode 字典序列删除 C++】316. Remove Duplicate Letters 1081. Smallest Subsequence of Distinct Characters

316. Remove Duplicate Letters

1081. Smallest Subsequence of Distinct Characters

在这里插入图片描述

class Solution {
    
    
public:
    string removeDuplicateLetters(string s) {
    
    
        vector<int> remain_cnt(26, 0);
        for(auto ch : s) remain_cnt[ch - 'a']++;

        vector<char> stack(s.size());
        int top = -1;
        for(auto ch : s) {
    
    
            if(find(stack.begin(), stack.begin()+top+1, ch) == stack.begin()+top+1) {
    
    
                while(top != -1 && stack[top] > ch && remain_cnt[stack[top] - 'a']) top--;
                stack[++top] = ch;
            }
            remain_cnt[ch - 'a']--;
        }
        string ans = "";
        for(int ii = 0; ii <= top; ii++) ans += stack[ii];
        return ans;
    }
};

猜你喜欢

转载自blog.csdn.net/m0_37454852/article/details/114368261