Given a string s
, 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.
Note: This question is the same as 1081: https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/
Example 1:
Input: s = "bcabc" Output: "abc"
Example 2:
Input: s = "cbacdcbc" Output: "acdb"
Constraints:
1 <= s.length <= 104
s
consists of lowercase English letters.
解题思路:此题使用statck保存不重复的字符串,在遍历主串时使用visited检查是否栈中已经有字符串,如果已经压入栈则继续遍历,为了保证压入栈中的字符串为最小字典序,每次入栈的时候和栈顶进行比对,如果小于栈顶则要考虑要不要把栈顶pop,依据的是m_count中记录的字符个数,如果m_count中对应字符大于0,则后面还有字符可以pop,否则压栈。代码如下:
class Solution {
public:
string removeDuplicateLetters(string s) {
if(s.size() < 2)
return s;
stack<char> st;
unordered_map<char, bool>visited;
unordered_map<char, int>m_count;
for(auto c:s)
{
m_count[c]++;
}
for(int i = 0; i < s.size(); i++)
{
if(visited[s[i]])
{
m_count[s[i]]--;
continue;
}
while(!st.empty() && s[i] < st.top() && m_count[st.top()] > 0)
{
visited[st.top()] = false;
st.pop();
}
st.push(s[i]);
visited[s[i]] =true;
m_count[s[i]]--;
}
string str = "";
while(!st.empty())
{
str = st.top() + str;
st.pop();
}
return str;
}
};