953. Verifying an Alien Dictionary (easy)
In an alien language, surprisingly they also use english lowercase letters, but possibly in a different
order
. Theorder
of the alphabet is some permutation of lowercase letters.Given a sequence of
words
written in the alien language, and theorder
of the alphabet, returntrue
if and only if the givenwords
are sorted lexicographicaly 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 b也是从左到右扫描判断,当出现a b的某位j判断出 a[j] < b[j]时 这两个单词就满足外星字母序,即不用往后判断了,直接跳到下一对a b
class Solution:
def isAlienSorted(self, words, order):
"""
:type words: List[str]
:type order: str
:rtype: bool
"""
#Adjacent compare
length = len(words)
for i in range(length-1):
a = words[i]
b = words[i+1]
minlen = min(len(a),len(b))
for j in range(minlen):
if order.index(a[j]) < order.index(b[j]):break
elif order.index(a[j]) > order.index(b[j]):return False
elif j == minlen - 1 and len(b) < len(a):return False
return True