Remove Duplicate Letters
Thoughts
Code
class Solution {
public String removeDuplicateLetters(String s) {
int[] amount = new int[26];
boolean[] visited = new boolean[26];
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
amount[c - 'a']++;
}
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (amount[c - 'a'] > 0 && !visited[c - 'a']) {
while (!stack.isEmpty() && amount[stack.peek() - 'a'] > 0 && stack.peek() > c) {
visited[stack.pop() - 'a'] = false;
}
stack.push(c);
visited[c - 'a'] = true;
}
amount[c - 'a']--;
}
String res = "";
for (Character c : stack) {
res = res + c;
}
return res;
}
}Analysis
Last updated