Leetcode 316. 去除重复字母
题目
给你一个仅包含小写字母的字符串,请你去除字符串中重复的字母,使得每个字母只出现一次。需保证返回结果的字典序最小(要求不能打乱其他字符的相对位置)。
测试样例
示例 1:
输入: "bcabc"
输出: "abc"
示例 2:
输入: "cbacdcbc"
输出: "acdb"
题解
栈应用
先用哈希表统计字符串中每个字符出现的次数。同时用一个哈希表来表明这个字符是否已经被我们使用。如果当前字符没有被使用过,用栈维持一个递增栈,需要注意的一点是,只有栈顶元素在后面还会出现时才出栈。详细过程见代码
代码
string removeDuplicateLetters(string s) {
unordered_map<char,int> mp; //统计字符出现次数
unordered_map<char,bool> isIn; //是否已经使用该字符
int len = s.length();
for(int i=0; i<len; i++){
mp[s[i]]++;
isIn[s[i]] = false;
}
stack<char> ans;
for(int i=0; i<len; i++){
if(ans.empty()){
ans.push(s[i]);
isIn[s[i]] = true;
}else if(!isIn[s[i]]){ //未使用该字符时才考虑
while(!ans.empty() && s[i] < ans.top()){ //维持递增栈
if(mp[ans.top()]){ //需保证后面还会出现该字符
isIn[ans.top()] = false;
ans.pop();
}else break;
}
ans.push(s[i]);
isIn[s[i]] = true;
}
mp[s[i]]--;
}
string ansS;
while(!ans.empty()){
ansS += ans.top();
ans.pop();
}
reverse(ansS.begin(),ansS.end());
return ansS;
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-duplicate-letters
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。