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
| class Solution { public String customSortString(String order, String s) { char[] sArray = s.toCharArray(); StringBuilder[] charCount = new StringBuilder[26]; for (char letter : sArray) { if (charCount[letter - 'a'] == null) { charCount[letter - 'a'] = new StringBuilder(); } charCount[letter - 'a'].append(letter); } char[] orderArray = order.toCharArray(); StringBuilder ans = new StringBuilder(); for (char letter : orderArray) { if (charCount[letter - 'a'] != null) { ans.append(charCount[letter - 'a']); charCount[letter - 'a'] = null; } } for (int i = 0; i < charCount.length; i++) { if (charCount[i] != null) { ans.append(charCount[i]); } } return ans.toString(); } }
|
记录s中每个字母的count, 然后再遍历order中的字母, 看是否在s中出现过, 如果出现过, 就把所有出现的加到letter上. 最后在把count中不出现在order中但是出现在s中的字母加到ans中即可.
时间复杂度: O(m + n)
空间复杂度: O(n)
m是order的长度, n是s的长度.