-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemoveDuplicatesStringWala.java
More file actions
29 lines (29 loc) · 1.19 KB
/
RemoveDuplicatesStringWala.java
File metadata and controls
29 lines (29 loc) · 1.19 KB
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
class Solution {
public String smallestSubsequence(String s) {
// Same as LeetCode 316
HashMap<Character, Integer> map = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
map.put(ch, i);
}
Stack<Character> S = new Stack<>();
boolean[] visited = new boolean[26];
for (int i = 0; i < s.length(); i++) {
char curr = s.charAt(i);
if (visited[curr - 'a']) {
continue;
}
while (S.size() > 0 && curr<S.peek() && i < map.get(S.peek())) {
visited[S.peek() - 'a'] = false;
S.pop();
}
visited[curr - 'a'] = true;
S.push(curr);
}
StringBuilder sb = new StringBuilder();
while (!S.isEmpty()) {
sb.append(S.pop());
}
return sb.reverse().toString();
}
}