0953. Verifying an Alien Dictionary
Easy | String + Hash Table | 28 ms (96.12%), 14.2 MB (91.25%)
Input: words = ["hello","leetcode"], order = "hlabcdefgijkmnopqrstuvwxyz"
Output: true
Explanation:
As 'h' comes before 'l' in this language, then the sequence is sorted.
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.
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.class Solution:
def isAlienSorted(self, words: List[str], order: str) -> bool:
# ==================================================
# String =
# ==================================================
# time : O(M), M is the total number of chars in words
# space : O(1)
table = dict()
for i in range(len(order)): table[order[i]] = i
for i in range(len(words) - 1):
for j in range(len(words[i])):
# (current string's length > adjacent string's length)
if j+1 > len(words[i+1]): return False
if words[i][j] != words[i+1][j]:
if table[words[i][j]] > table[words[i+1][j]]: return False
break
return TrueLast updated