https://lina.bitcron.com/post/code/2018-summer-fb-intern-mian-jing
Sort an input string using an arbitrary alphabetFor example: custom alphabet: xyzabcinput to sort according to custom alphabet: cyxzoutput according to custom alphabet: xyzc
//O(n)
public String sortedStringWithCustomAlphabet(String s, String alphabet){
if(s==null||alphabet==null)return null;
Map<Character,Integer> map = new HashMap<Character,Integer>();
for(int i = 0; i < s.length();i++){
if(!map.containsKey(s.charAt(i))){
map.put(s.charAt(i),1);
}else{
map.put(s.charAt(i),map.get(s.charAt(i))+1);
}
}
StringBuilder sb = new StringBuilder(s.length());
for(char c : alphabet.toCharArray()){ //扫描字母表排序
if(!map.containsKey(c))continue;
int t = map.get(c);
while(t-->0){
sb.append(c);
}
}
return sb.toString();
}