316. Remove Duplicate Letters
Remove Duplicate Letters
Solution
public class Solution {
public String removeDuplicateLetters(String s) {
if (s == null || s.length() <= 1) return s;
int[] dict = new int[26];
for (char c : s.toCharArray()) {
dict[c - 'a'] += 1;
}
Stack<Character> stack = new Stack<>();
int index = 0;
while (index < s.length()) {
char currentChar = s.charAt(index);
if (!stack.contains(currentChar)) {
while (!stack.isEmpty() && dict[stack.peek() - 'a'] >= 1 && currentChar < stack.peek()) {
stack.pop();
}
stack.push(currentChar);
}
dict[currentChar - 'a'] -= 1;
index++;
}
StringBuffer sb = new StringBuffer();
while (!stack.isEmpty()) {
sb.append(stack.pop());
}
return sb.reverse().toString();
}
}Last updated