题目描述:
某种外星语也使用英文小写字母,但可能顺序 order 不同。字母表的顺序(order)是一些小写字母的排列。
给定一组用外星语书写的单词 words,以及其字母表的顺序 order,只有当给定的单词在这种外星语中按字典序排列时,返回 true;否则,返回 false。
做题记录:
这一道题可以理解为排序字母的变种题目,如果说正常的排序题目是按照26个英文字母正常排序,那么“外星语言”则是有他们自己特殊的字母排序;在正常排序的时候,我们是按照字母的ASCII码来进行比较,那么在“外星语言的”环境下,我们按照他们的字母排序,来为这26个字母构造独特的ASCII码排序,然后按照他们的ASCII码比较即可。
附上代码:
public class Solution {
private int[] nums = new int[26];
public boolean isAlienSorted(String[] words, String order) {
orderLetter(order);
if (words.length <= 1) {
return true;
}
String word1;
String word2;
for (int i = 0, j = 1; j < words.length; i = j, j++) {
word1 = words[i];
word2 = words[j];
if (!compare(word1, word2)) {
return false;
}
}
return true;
}
public void orderLetter(String order) {
int index = 0;
char[] chars = order.toCharArray();
for (char c : chars) {
nums[c - 'a'] = index;
index++;
}
}
//如果word1和word2按照顺序排列则返回true,否则返回false;
public boolean compare(String word1, String word2) {
int length1 = word1.length();
int length2 = word2.length();
int i = 0;
while (i < length1 && i < length2) {
int order1 = nums[word1.charAt(i) - 'a'];
int order2 = nums[word2.charAt(i) - 'a'];
if (order1 != order2) {
return order1 < order2;
}
i++;
}
return length1 <= length2;
}
}