953. Verifying an Alien Dictionary
Problem 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:
1 | Input: words = ["hello","leetcode"], order = "hlabcdefgijkmnopqrstuvwxyz" |
Example 2:
1 | Input: words = ["word","world","row"], order = "worldabcefghijkmnpqstuvxyz" |
Example 3:
1 | Input: words = ["apple","app"], order = "abcdefghijklmnopqrstuvwxyz" |
Constraints:
1 <= words.length <= 100
1 <= words[i].length <= 20
order.length == 26
- All characters in
words[i]
andorder
are English lowercase letters.
Solution:
Build a transform mapping from order
,Find all alien words with letters in normal order.
For example, if we have order = "xyz..."
We can map the word "xyz"
to "abc"
or "123"
Then we check if all words are in sorted order.
For example,words = [“hello”,”leetcode”]order = “hlabcdefgijkmnopqrstuvwxyz”
- Create a dic, key is each word in new order, value is its index, which means its new position in the new order.
- Transform the list of words into its index in new order.words =
["hello","leetcode"] -> [[0, 6, 1, 1, 14], [1, 6, 6, 19, 4, 14, 5, 6]]
zip()
will zip 2 element one by one,zip(words, words[1:])
here will combine first element(words[0]) in words with words[1], so we can compare current element with next element: word[0]->word[1], word[1]->word[2]
1 | class Solution: |
time complexity: $O(NS)$, N words, length = S
space complexity: $O(1)$
reference:
related problem: