953. Verifying an Alien Dictionary
LeetCode 953. Verifying an Alien Dictionary
Description
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 lexicographicaly in this alien language.
Example 1:
Example 2:
Constraints:
1 <= words.length <= 100
1 <= words[i].length <= 20
order.length == 26
All characters in
words[i]
andorder
are English lowercase letters.
Tags
Hash Table
Solution
Before checking, we build a dictionary to map each character from order
to its index. We compare each pair of adjacent words. Iterate over the former word.
If the pointer on the
word[i]
is beyond the length ofword[i+1]
, return false. Because the latter mush longer than or equal to the former word if they share the same prefix;If
words[i][j] != words[i+1][j]
, retrieve the indices of both and they must obey the alien dictionary order. After evaluating, break here because the remain part will not be considered.
Complexity
Code
Reference
Last updated
Was this helpful?