In order to get the lexicographical order, we need to always update the new order once we found it is up-datable. (This sentence actually is non-sense....)
An Example will make this clear.
Suppose we have the string "bcabc"
My first thought was to use stack, stack can absolutely keep the lexicographical order. If we found a smaller char, we pop-out the big ones. But, there is one problem. For example,
if it is the only character in this string, we can't pop-out in any case (once we pop it, it is gone :( ). A hashMap might be perfect for this then, we use a hashmap to remember the count of the character afterwards.
So, for example "bcabc", we use a hashmap to remember the counts of characters. map[b] = 2, map[c] = 2, map[a] = 1.
Let's start pushing into the stack.
1:
stack: b
count: map[b] = 1, map[c] = 2, map[a] = 1.
2:
stack: b, c
count: map[b] = 1, map[c] = 1, map[a] = 1.
3:
stack: b, c, a (but a is smaller then b, c, and we know that there is b and c afterwards) ---> thus, we pop out b, c, and keep a in stack.
count: map[b] = 1, map[c] = 1, map[a] = 0.
4:
stack: a, b
count: map[b] = 0, map[c] = 1, map[a] = 0.
5:
stack: a, b, c
count: map[b] = 0, map[c] = 0, map[a] = 0. ---> done: output "abc"
#include <string>
#include <stack>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
/*
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.
Example:
Given "bcabc" --> return "abc"
Given "cbacdcbc" --> return "acdb"
*/
// need to check whether the stack already has it or not. If not exists, push directly.
bool notExistInStack(stack<char> ascending, char a) {
if(ascending.empty()) return true;
stack<char> tmp;
while(!ascending.empty()) {
char top = ascending.top();
if(top == a) return false;
tmp.push(top);
ascending.pop();
}
while(!tmp.empty()) {
char top = tmp.top();
ascending.push(top);
tmp.pop();
}
return true;
}
string removeDuplicateLetters(string s) {
vector<int> map(256, 0);
for(int i = 0; i < s.size(); ++i) {
map[s[i]]++;
}
stack<char> ascending;
for(int i = 0; i < s.size(); ++i) {
while(!ascending.empty() && (ascending.top() > s[i] && map[ascending.top()] > 0)) {
map[ascending.top()]--;
ascending.pop();
}
if(notExistInStack(ascending, s[i])) {
ascending.push(s[i]);
map[s[i]]--;
}
}
string res = "";
while(!ascending.empty()) {
char top = ascending.top();
ascending.pop();
res = top + res;
}
return res;
}
int main(void) {
string res = removeDuplicateLetters("bcabc");
cout << res << endl;
string res_1 = removeDuplicateLetters("cbacdcbc");
cout << res_1 << endl;
}
本文介绍了一种算法,用于从只包含小写字母的字符串中移除重复字符,同时确保结果字符串在字典序上是最小的。通过使用栈和哈希映射的数据结构,算法能够在O(n)时间内完成操作。
1709

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



