标签:mono ble lan 最大 moved leetcode turn ted 返回结果
给你一个字符串 s ,请你去除字符串中重复的字母,使得每个字母只出现一次。需保证 返回结果的字典序最小(要求不能打乱其他字符的相对位置)。
注意:该题与 1081 https://leetcode-cn.com/problems/smallest-subsequence-of-distinct-characters 相同
示例 1:
输入:s = "bcabc"
输出:"abc"
示例 2:
输入:s = "cbacdcbc"
输出:"acdb"
提示:
1 <= s.length <= 104
s 由小写英文字母组成
class Solution {
public:
string removeDuplicateLetters(string s) {
unordered_map<char, int> rec;
for(auto c:s){
++rec[c];
}
stack<char> monotonousStack;
unordered_set<char> visited;
for(auto c:s){
if(visited.count(c) == 0){
while(!monotonousStack.empty() && c < monotonousStack.top()
&& rec[monotonousStack.top()] > 0){
visited.erase(monotonousStack.top());
monotonousStack.pop();
}
monotonousStack.push(c);
visited.insert(c);
}
--rec[c];
}
string ans(monotonousStack.size(), ‘a‘);
int i = monotonousStack.size()-1;
while(!monotonousStack.empty()){
ans[i--] = monotonousStack.top();
monotonousStack.pop();
}
return ans;
}
};
标签:mono ble lan 最大 moved leetcode turn ted 返回结果
原文地址:https://www.cnblogs.com/wasi-991017/p/14162520.html