-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathremoveDuplicateLetters.cpp
37 lines (28 loc) · 950 Bytes
/
removeDuplicateLetters.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Solution {
public:
string removeDuplicateLetters(string s) {
vector<int> lastIndex(26, -1);
vector<bool> seen(26, false);
int n = s.size();
stack<int> sStack;
for(int i = 0; i < n; ++i)
lastIndex[s[i] - 'a'] = i;
for(int i = 0; i < n; ++i) {
int ch = s[i] - 'a';
if(seen[ch]) continue;
while(!sStack.empty() && sStack.top() > ch && i < lastIndex[sStack.top()]) {
seen[sStack.top()] = false;
sStack.pop();
}
sStack.push(ch);
seen[ch] = true;
}
string result = "";
while(!sStack.empty()) {
result.push_back((char) sStack.top() + 'a');
sStack.pop();
}
reverse(result.begin(), result.end());
return result;
}
};