Table of contents
Question requirements
- Remove some duplicate elements
- Keep the original order
- Minimize lexicographic order
Ideas
- Traverse a string and maintain a stack
- If the current character is already on the stack, skip it directly (see the program for details)
- When the top element of the stack > the current element , pop the top of the stack and then push it into the stack
- If the top element of the stack is the last survivor, then refuse to pop out of the stack (the question requires that only duplicate characters can be deleted)
- When the top element of the stack < the current element , then it is pushed onto the stack smoothly.
If you still don't understand...
(Then it’s hopeless)
Then take a look at the program. There are comments in the program.
Likou submits AC code
class Solution {
public:
string removeDuplicateLetters(string s) {
vector<int> times(260, 0); //初始化 每一个字符在后续出现次数
string sta = ""; //用string当作栈本体
for (auto c : s) times[c] ++; //统计次数
for (auto c : s) {
//如果栈中已经有了,不给进,该字符次数--
if (sta.find(c) != string::npos) {
times[c] --;
continue;
}
//栈非空 如果栈顶 > 当前元素 但是得保证必须是最后一个幸存者,才能出栈
while(sta.size() && sta.back() > c && times[sta.back()])
sta.pop_back();
//新元素入栈
sta.push_back(c);
times[c] --; //次数--
}
return sta;
}
};
In addition, it is also thoughtfully posted
C++ code
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
string s;
cin >> s;
vector<int> times(260, 0); //初始化 每一个字符在后续出现次数
string sta = ""; //用string当作栈本体
for (auto c : s) times[c] ++; //统计次数
for (auto c : s) {
//如果栈中已经有了,不给进,该字符次数--
if (sta.find(c) != string::npos) {
times[c] --;
continue;
}
//栈非空 如果栈顶 > 当前元素 但是得保证必须是最后一个幸存者,才能出栈
while(sta.size() && sta.back() > c && times[sta.back()])
sta.pop_back();
//新元素入栈
sta.push_back(c);
times[c] --; //次数--
}
cout << sta;
}
Question portal: 316. Remove duplicate letters - LeetCode