问题描述
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:
Given “bcabc”
Return “abc”Given “cbacdcbc”
Return “acdb”Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.解决思路
首先统计每个字符出现的次数,构建一个栈,栈满足栈底的元素小于栈顶的元素(但如果剩余的出现次数为0了,则不需要满足这个条件)。然后一直维持这个栈即可。总而言之是贪心算法加栈的解决方案。代码
class Solution {
public:
string removeDuplicateLetters(string s) {
if (s == "")
return s;
int count[26] = {0};
for (int i = 0; i < s.length(); ++i)
++count[s[i]-'a'];
bool isvisit[26] = {0};
stack<char> st;
for (int i = 0; i < s.length(); ++i) {
int index = s[i]-'a';
--count[index];
if (isvisit[index])
continue;
while(!st.empty() && s[i] < st.top() && count[st.top()-'a'] != 0) {
isvisit[st.top()-'a'] = false;
st.pop();
}
st.push(s[i]);
isvisit[index] = true;
}
string res = "";
while(!st.empty()) {
res += st.top();
st.pop();
}
reverse(res.begin(),res.end());
return res;
}
};