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.
Example 1:
Input:"bcabc"
Output:"abc"
Example 2:
Input:"cbacdcbc"
Output:"acdb"
本文主要参考博文:here。
class Solution {
public:
string removeDuplicateLetters(string s) {
int m[256] = { 0 };
bool used[256] = { false };
string res = "0";
for (auto c : s) m[c]++;
for (auto c : s) {
m[c]--;
if (used[c]) continue;
while (c < res.back() && m[res.back()]) {
used[res.back()] = false;
res.pop_back();
}
res += c;
used[c] = true;
}
return res.substr(1);
}
};