316. Remove Duplicate Letters
Difficulty: Hard
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”
思路
首先可以想到的是使用容器储存字母,容器尾端的字母’c’比当前遍历的字母’a’比大时,需要把’c’从容器中排除(可能不只排出一次),再存入’a’,因此选取stack容器;
当排除’c’时,必须满足以下条件:在’a’之后还存在’c’,因此需要记录对每个元素出现的次数;
当出现已存入容器的字母时,不能再存入该字母,因此还需要知道字母是否存在容器中。
代码
[C++]
class Solution {
public:
string removeDuplicateLetters(string s) {
string res;
vector<int> count(26, 0);
vector<bool> exist(26, false);
stack<char> str;
for (int i = 0; i < s.size(); ++i)
count[s[i] - 'a']++;
for (int i = 0; i < s.size(); ++i) {
if (exist[s[i] - 'a']) {
count[s[i] - 'a']--;
continue;
}
while (!str.empty() && str.top() > s[i] && count[str.top() - 'a']) {
exist[str.top() - 'a'] = false;
str.pop();
}
str.push(s[i]);
exist[s[i] - 'a'] = true;
count[s[i] - 'a']--;
}
while (!str.empty()) {
res = str.top() + res;
str.pop();
}
return res;
}
};
本文介绍了一种算法,用于从字符串中移除重复的字母,确保每个字母只出现一次,并保持结果字符串在字典序上最小。通过使用栈来实现这一过程。

1693

被折叠的 条评论
为什么被折叠?



