题目链接:https://leetcode-cn.com/problems/remove-duplicate-letters/
难度:中等
思路:单调栈
代码:
class Solution {
public:
string removeDuplicateLetters(string s) {
//利用字符的ASCII码值作为数组索引,保存该字符出现的次数,用于判断字符串后面是否还存在该字符
vector<int> count(256);
for (auto c: s)
count[c]++;
string res;
stack<char> stk;
vector<bool> inStack(256); //用于判断字符是否已在栈中,保证stk栈中不存在重复字符
for (auto c: s)
{
count[c]--; //每遍历一个字符就将对应的次数减1
if (inStack[c]) continue;
while (!stk.empty() && stk.top() > c) //为满足 返回结果的字典序最小 这个要求,需判断栈顶元素是否大于当前字符
{
if (count[stk.top()] == 0) break; //如果count数组中已经不存在该字符了,说明字符串后面已经没有该字符,则中止pop()
char top = stk.top();
stk.pop();
inStack[top] = false; //否则,字符串后面还存在该字符,可以pop()
}
stk.push(c); //压栈,并将该字符在数组中的对应位置设为true
inStack[c] = true;
}
while (!stk.empty())
{
char c = stk.top();
stk.pop();
res.push_back(c);
}
reverse(res.begin(), res.end()); //栈的结果需要翻转
return res;
}
};
难点:
- 也就是题目要求的第三点 返回结果的字典序最小,用count数组保存字符出现的次数,在遍历时进行判断;如果该字符出现的次数不等于0则说明字符串后面还有该字符,可以进行pop,否则压栈。