1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| class Solution { public String removeDuplicateLetters(String s) { boolean[] seen = new boolean[26]; int[] num = new int[26]; char[] cs = s.toCharArray(); for (char c : cs) num[c - 'a']++; StringBuilder ans = new StringBuilder(); for (char c : cs) { if (!seen[c - 'a']) { while (ans.length() > 0 && ans.charAt(ans.length() - 1) > c && num[ans.charAt(ans.length() - 1) - 'a'] > 0) { seen[ans.charAt(ans.length() - 1) - 'a'] = false; ans.deleteCharAt(ans.length() - 1); } seen[c - 'a'] = true; ans.append(c); } num[c - 'a']--; } return ans.toString(); } }
|