这里找到更简单的一种做法
class Solution {
public:
string removeDuplicateLetters(string s) {
string a = s.substr(2).replace(0, 1, "q");
if(s.size() < 2) return s;
int count[150] = {0}, add[150] = {0};
string ans;
for(char c : s){
count[c]++;
}
for(char c : s){
count[c]--;
if(add[c] != 0) continue;
while(!ans.empty() && ans.back() > c && count[ans.back()] > 0){
add[ans.back()] = 0;
ans.pop_back();
}
ans.push_back(c);
add[c] = 1;
}
return ans;
}
};
附上标答做法,很简练,是一个一个char的确定的,利用了递归:
public class Solution {
public String removeDuplicateLetters(String s) {
int[] cnt = new int[26];
int pos = 0; // the position for the smallest s[i]
for (int i = 0; i < s.length(); i++) cnt[s.charAt(i) - 'a']++;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) < s.charAt(pos)) pos = i;
if (--cnt[s.charAt(i) - 'a'] == 0) break;
}
return s.length() == 0 ? "" : s.charAt(pos) + removeDuplicateLetters(s.substring(pos + 1).replaceAll("" + s.charAt(pos), ""));
}
}