public String[] wordSort(char[] alphabet, String[] words) {
Map<Character, Integer> map = getAlphabetMap(alphabet);
Arrays.sort(words, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return getWeight(map, o1, o2);
}
});
return words;
}
private int getWeight(Map<Character, Integer> map, String o1, String o2) {
int weight = 0;
for (int i = 0; i < Math.min(o1.length(), o2.length()); i++) {
Integer w1 = map.get(o1.charAt(i));
Integer w2 = map.get(o2.charAt(i));
if (w1 == w2) {
continue;
}
return w2 - w1;
}
return o1.length() - o2.length();
}
private Map<Character, Integer> getAlphabetMap(char[] alphabet) {
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < alphabet.length; i++) {
map.put(alphabet[i], i);
}
return map;
}