上面的超链接链向原题,原题的题意是给定新的字母表,让我们用新字母表的顺序给给定的字符串按照字典排序法排序。
思路:
其实题意就是字母的一对一替换,将得到的字符串用原来的字母表示出来,将结果进行排序后,反编译回现在的字母表示即可。
代码如下:
public class Solution { /** * @param alphabet: the new alphabet * @param words: the original string array * @return: the string array after sorting */ public String[] wordSort(char[] alphabet, String[] words) { String[][] temp = new String[words.length][2]; for (int i = 0; i < temp.length; i++) { temp[i][0] = words[i]; temp[i][1] = calculate(words[i], alphabet); } Arrays.sort(temp, new Comparator<String[]>() { public int compare(String[] s1, String[] s2) { if (s1[1].startsWith(s2[1])) { return 1; } if (s2[1].startsWith(s1[1])) { return -1; } for (int i = 0; i < s1[1].length() && i < s2[1].length(); i++) { char c1 = s1[1].charAt(i); char c2 = s2[1].charAt(i); if (c1 != c2) { if (c1 > c2) { return 1; } else { return -1; } } } return 0; } }); String[] ret = new String[temp.length]; for (int i = 0; i < ret.length; i++) { ret[i] = temp[i][0]; } return ret; } private String calculate(String string, char[] alphabet) { String normal = "abcdefghijklmnopqrstuvwxyz"; String unusual = new String(alphabet); StringBuilder strb = new StringBuilder(); int index; for (int i = 0; i < string.length(); i++) { index = unusual.indexOf(string.charAt(i)); strb.append(normal.charAt(index)); } return strb.toString(); } }