Skip to content

Commit 0e64555

Browse files
Create 0316-remove-duplicate-letters.java
1 parent 8c00b13 commit 0e64555

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
class Solution {
2+
public String removeDuplicateLetters(String s) {
3+
Set<Character> seen = new HashSet<>();
4+
HashMap<Character, Integer> last = new HashMap<>();
5+
for(char c : s.toCharArray()){
6+
if(!last.containsKey(c))
7+
last.put(c, s.lastIndexOf(c));
8+
}
9+
Stack<Character> stack = new Stack();
10+
for(int i = 0; i < s.length(); i++){
11+
char c = s.charAt(i);
12+
if(seen.contains(c))
13+
continue;
14+
while(!stack.isEmpty() && stack.peek() > c && i < last.get(stack.peek()))
15+
seen.remove(stack.pop());
16+
stack.push(c);
17+
seen.add(c);
18+
}
19+
StringBuilder sb = new StringBuilder();
20+
for(char c: stack)
21+
sb.append(c);
22+
return sb.toString();
23+
}
24+
}

0 commit comments

Comments
 (0)