某种外星语也使用英文小写字母,但可能顺序 order 不同。字母表的顺序(order)是一些小写字母的排列。
给定一组用外星语书写的单词 words,以及其字母表的顺序 order,只有当给定的单词在这种外星语中按字典序排列时,返回 true;否则,返回 false。
class Solution {
int[] ord = new int[26];
public boolean isAlienSorted(String[] words, String order) {
for(int i = 0;i < 26;i++){
ord[order.charAt(i) - 'a'] = i;
}
int n = words.length;
for (int i = 1; i < n; i++) {
if (check(words[i - 1], words[i]) > 0) return false;
}
return true;
}
int check(String a, String b) {
int n = a.length(), m = b.length();
int i = 0, j = 0;
while (i < n && j < m) {
int c1 = a.charAt(i) - 'a', c2 = b.charAt(j) - 'a';
if (c1 != c2) return ord[c1] - ord[c2];
i++; j++;
}
if (i < n) return 1;
if (j < m) return -1;
return 0;
}
}
执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户
内存消耗:39.9 MB, 在所有 Java 提交中击败了66.90%的用户



