Given a string which contains only lowercase letters, remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.
Example 1:
Input:"bcabc"
Output:"abc"
Example 2:
Input:"cbacdcbc"
Output:"acdb"
/* 去重 是最后保留的字符串的字典序 最小
* 贪心? 用滑动窗口(栈)保存之前的东西 当前元素小于栈顶 且栈顶元素咋后面还能再次出现时 栈顶元素出栈 否则入栈
* 但是特例: ccacbaba
* acab
* 所以还应该用一个flag表示 各个字符是否已经在栈中
* */
class Solution {
public:
string removeDuplicateLetters(string s) {
vector<int> cnt(26, 0);
vector<bool> visit(26, false);
for(char &c : s) cnt[c-'a']++;
string ret="";// 哨兵
for(char &c: s){
cnt[c-'a']--;
if(visit[c-'a']) continue;
while(ret.size()>0 && cnt[ret.back()-'a'] && c <= ret.back()){
visit[ret.back()-'a']=false;
ret.pop_back();
}
visit[c-'a']=true;
ret.push_back(c);
}
return ret;
}
};