给你一个字符串 s ,请你去除字符串中重复的字母,使得每个字母只出现一次。需保证 返回结果的字典序最小(要求不能打乱其他字符的相对位置)。 注意:该题与 1081 https://leetcode-cn.com/problems/smallest-subsequence-of-distinct-characters 相同 示例 1: 输入:s = "bcabc" 输出:"abc" 示例 2: 输入:s = "cbacdcbc" 输出:"acdb" 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/remove-duplicate-letters 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:没看懂字典序意思 以为从后往前去重(错误)
public static String removeDuplicateLetters(String s) { int len = s.length()-1; String[] sp = s.split(""); List list = new ArrayList(); for (int i=len;i>0;i--){ if(sp[i]!=null&&!list.contains(sp[i])){ list.add(sp[i]); } } StringBuilder re = new StringBuilder(String.join("", list)).reverse(); return re.toString(); }
以下官方解答
public String removeDuplicateLetters(String s) { boolean[] vis = new boolean[26]; int[] num = new int[26]; for (int i = 0; i < s.length(); i++) { num[s.charAt(i) - 'a']++; } StringBuffer sb = new StringBuffer(); for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); if (!vis[ch - 'a']) { while (sb.length() > 0 && sb.charAt(sb.length() - 1) > ch) { if (num[sb.charAt(sb.length() - 1) - 'a'] > 0) { vis[sb.charAt(sb.length() - 1) - 'a'] = false; sb.deleteCharAt(sb.length() - 1); } else { break; } } vis[ch - 'a'] = true; sb.append(ch); } num[ch - 'a'] -= 1; } return sb.toString(); }