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
| class Solution { public String removeDuplicateLetters(String s) { int[] cnt = new int[26]; for (int i = 0; i < s.length(); i++) { cnt[s.charAt(i) - 'a']++; }
boolean[] in = new boolean[26]; Deque<Character> stack = new LinkedList<>(); for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); if (!in[ch - 'a']) { while (!stack.isEmpty() && stack.peek() > ch) { if (cnt[stack.peek() - 'a'] > 0) { in[stack.peek() - 'a'] = false; stack.pop(); } else { break; } } stack.push(ch); in[ch - 'a'] = true; } cnt[ch - 'a']--; } StringBuilder sb = new StringBuilder(); for (char ch : stack) { sb.append(ch); } return sb.reverse().toString(); } }
|