描述
Given a string which contains only lowercase letters, remove duplicate letters so that every letter appear once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.
您在真实的面试中是否遇到过这个题?
是
样例
Given "bcabc"
Return "abc"
Given "cbacdcbc"
Return "acdb"
class Solution {
public:
/**
* @param s: a string
* @return: return a string
*/
string removeDuplicateLetters(string &s) {
// write your code here
vector<int> m(256,0);
vector<int> visited (256,0);
string res = "0";
for (auto a : s) ++m[a];
for (auto a : s) {
--m[a];
if (visited[a]) continue;
while (a < res.back() && m[res.back()]) {
visited[res.back()] = 0;
res.pop_back();
}
res += a;
visited[a] = 1;
}
return res.substr(1);
}
};