[LeetCode] Remove Duplicate Letters

316. Remove Duplicate Letters

Given a string s, remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.

  • Time : O(n)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
string removeDuplicateLetters(string s) {
int arr[26]{0,};
int contain = 0;
for(auto& ch : s) ++arr[ch-'a'];
string res;
for(auto& ch : s) {
while(!res.empty() && res.back() > ch && arr[res.back() - 'a'] && !(contain & (1<<(ch-'a')))) {
contain ^= (1<<(res.back()-'a'));
res.pop_back();
}
--arr[ch-'a'];
if(!(contain & (1<<(ch-'a')))) {
res += ch;
contain |= (1<<(ch-'a'));
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/11/PS/LeetCode/remove-duplicate-letters/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.