316 Remove Duplicate Letters
1. Question
2. Implementation
class Solution {
public String removeDuplicateLetters(String s) {
int[] count = new int[256];
boolean[] visited = new boolean[256];
Stack<Character> stack = new Stack<>();
for (char c : s.toCharArray()) {
++count[c];
}
for (char c : s.toCharArray()) {
--count[c];
if (visited[c]) {
continue;
}
while (!stack.isEmpty() && stack.peek() > c && count[stack.peek()] != 0) {
visited[stack.peek()] = false;
stack.pop();
}
stack.push(c);
visited[c] = true;
}
StringBuilder res = new StringBuilder();
while (!stack.isEmpty()) {
res.append(stack.pop());
}
return res.reverse().toString();
}
}3. Time & Space Complexity
Last updated