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.
Input:
words =["hello","leetcode"], order ="hlabcdefgijkmnopqrstuvwxyz"Output:
trueExplanation: As 'h' comes before 'l'inthis language, then the sequence is sorted.
Example 2:
1
2
3
4
5
Input:
words =["word","world","row"], order ="worldabcefghijkmnpqstuvxyz"Output:
falseExplanation: As 'd' comes after 'l'inthis language, then words[0]> words[1], hence the sequence is unsorted.
Example 3:
1
2
3
4
5
Input:
words =["apple","app"], order ="abcdefghijklmnopqrstuvwxyz"Output:
falseExplanation: The first three characters "app" match, and the second string isshorter(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](https://en.wikipedia.org/wiki/Lexicographical_order)).
The main idea is to map each character in the alien language to its position in the given order string. By comparing each pair of adjacent words, we can check if the first differing character in the two words respects the alien order. If all pairs are in order, the list is sorted.
classSolution {
publicbooleanisAlienSorted(String[] words, String order) {
int[] pos =newint[26];
for (int i = 0; i < order.length(); i++) pos[order.charAt(i) -'a']= i;
for (int i = 0; i < words.length- 1; i++) {
String w1 = words[i], w2 = words[i+1];
int len = Math.min(w1.length(), w2.length());
boolean diff =false;
for (int j = 0; j < len; j++) {
if (w1.charAt(j) != w2.charAt(j)) {
if (pos[w1.charAt(j) -'a']> pos[w2.charAt(j) -'a']) returnfalse;
diff =true;
break;
}
}
if (!diff && w1.length() > w2.length()) returnfalse;
}
returntrue;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution:
defisAlienSorted(self, words: list[str], order: str) -> bool:
pos = {c: i for i, c in enumerate(order)}
for i in range(len(words) -1):
w1, w2 = words[i], words[i+1]
for j in range(min(len(w1), len(w2))):
if w1[j] != w2[j]:
if pos[w1[j]] > pos[w2[j]]:
returnFalsebreakelse:
if len(w1) > len(w2):
returnFalsereturnTrue