For example: custom alphabet: xyzabc
input to sort according to custom alphabet: cyxz
output according to custom alphabet: xyzc .
因为alphabet有限,可以 bucket sort,将alph存进map,设alpg 度为m,输 度n,那么空间
O(M), 时间max(m ,n 或者直接存 26个字 表的bucket,然后找找alph的顺序输出。空间26,时间 样
解法1:
public String changeAlph(String alph, String word) { int[] bucket = new int[26]; for (char c : word.toCharArray()) { bucket[c - ‘a‘]++; } StringBuilder sb = new StringBuilder(); for (char c : alph.toCharArray()) { while (bucket[c - ‘a‘]-- > 0) sb.append(c); } return sb.toString(); } 解法2: public String changeAlph(String alph, String word) { Map<Character, Integer> map = new HashMap<>(); for (char c : word.toCharArray()) { if (!map.containsKey(c)) map.put(c, 0); map.put(c, map.get(c) + 1); } StringBuilder sb = new StringBuilder(); for (char c : alph.toCharArray()) { if (map.containsKey(c)) { for (int i = 0; i < map.get(c); i++) sb.append(c); } } return sb.toString(); }