-
Notifications
You must be signed in to change notification settings - Fork 1
/
RemoveDuplicateLetters.java
38 lines (32 loc) · 1.11 KB
/
RemoveDuplicateLetters.java
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
38
package com.smlnskgmail.jaman.leetcodejava.medium;
import java.util.Stack;
// https://leetcode.com/problems/remove-duplicate-letters/
public class RemoveDuplicateLetters {
private final String input;
public RemoveDuplicateLetters(String input) {
this.input = input;
}
public String solution() {
int[] lastIndices = new int[26];
for (int i = 0; i < input.length(); i++) {
lastIndices[input.charAt(i) - 'a'] = i;
}
boolean[] seen = new boolean[26];
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < input.length(); i++) {
int c = input.charAt(i) - 'a';
if (!seen[c]) {
while (!stack.isEmpty() && stack.peek() > c && i < lastIndices[stack.peek()]) {
seen[stack.pop()] = false;
}
stack.push(c);
seen[c] = true;
}
}
StringBuilder result = new StringBuilder();
while (!stack.isEmpty()) {
result.append((char) (stack.pop() + 'a'));
}
return result.reverse().toString();
}
}