In an alien language, surprisingly, they also use English lowercase letters, but possibly in a different order. The order of the alphabet is some permutation of lowercase letters.
Given a sequence of words written in the alien language, and the order of the alphabet, return true if and only if the given words are sorted lexicographically in this alien language.
Example 1:
Input: words = [“hello”,“leetcode”], order = “hlabcdefgijkmnopqrstuvwxyz”
Output: true
Explanation: As ‘h’ comes before ‘l’ in this language, then the sequence is sorted.
Example 2:
Input: words = [“word”,“world”,“row”], order = “worldabcefghijkmnpqstuvxyz”
Output: false
Explanation: As ‘d’ comes after ‘l’ in this language, then words[0] > words[1], hence the sequence is unsorted.
Example 3:
Input: words = [“apple”,“app”], order = “abcdefghijklmnopqrstuvwxyz”
Output: false
Explanation: The first three characters “app” match, and the second string is shorter (in size.) According to lexicographical rules “apple” > “app”, because ‘l’ > ‘∅’, where ‘∅’ is defined as the blank character which is less than any other character (More info).
正常的字母顺序是a~z, 但是外星字典顺序是按order来的,
要判断words中的每个单词是不是升序排列的(按外星字典顺序)。
思路:
首先确定什么情况下word1 > word2,
通过看几个Example, 可以看出,
从左到右,出现word1中字母比对应位置的word2字母小时(不需要再比较后面的字母),判断word1 < word2, 是升序的。
当出现了word1中字母比对应位置的word2字母大时(不需要再比较后面的字母),判断word1 > word2, 不满足升序。
当对应位置字母相等时,继续比较下一个,到末尾还一样时,看谁的长度更长,如果word1的长度更长,那么word1 > word2。
理清了这个关系,就只需要比大小就行了,
正常情况下,a < b < … < z,
这里给了一个order作为字母顺序,只需要看哪个字母在前面,即谁的index在前,那么只要保存字母对应的index即可。
public boolean isAlienSorted(String[] words, String order) {
if(words.length == 1) return true;
int[] orderIdx = new int[26];
for(int i = 0; i < order.length(); i++) {
orderIdx[order.charAt(i)-'a'] = i;
}
for(int i = 1; i < words.length; i++) {
if(gt(words[i-1], words[i], orderIdx)) return false;
}
return true;
}
boolean gt(String w1, String w2, int[] order) {
int len = Math.min(w1.length(), w2.length());
for(int i = 0; i < len; i++) {
int diff = order[w1.charAt(i)-'a'] - order[w2.charAt(i)-'a'];
if(diff < 0) return false;
if(diff > 0) return true;
}
if(len < w1.length()) return true;
return false;
}