953. Verifying an Alien Dictionary
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:
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).
Constraints:
1 <= words.length <= 100
1 <= words[i].length <= 20
order.length == 26
All characters in
words[i]
andorder
are English lowercase letters.
bool isAlienSorted(vector<string>& words, string order) { // time: O(words_size * word_len); space: O(1)
vector<size_t> mp(26);
for (size_t i = 0; i < 26; ++i) mp[order[i] - 'a'] = i;
for (size_t i = 0; i < words.size() - 1; ++i) {
size_t cur_len = words[i].length(), nex_len = words[i + 1].length();
size_t len = min(cur_len, nex_len), j = 0;
for (; j < len; ++j) {
if (words[i][j] != words[i + 1][j]) break;
}
if (j == len && cur_len > nex_len) return false;
if (mp[words[i][j] - 'a'] > mp[words[i + 1][j] - 'a']) return false;
}
return true;
}
bool isAlienSorted(vector<string>& words, string order) { // time: O(words_size * word_len); space: O(1)
vector<size_t> mp(26);
for (size_t i = 0; i < 26; ++i) mp[order[i] - 'a'] = i;
return is_sorted(words.begin(), words.end(), [&mp](const string& str1, const string& str2) {
size_t len1 = str1.length(), len2 = str2.length();
for (size_t i = 0; i < min(len1, len2); ++i) {
char c1 = str1[i], c2 = str2[i];
if (c1 != c2) return mp[c1 - 'a'] < mp[c2 - 'a'];
}
return len1 < len2;
});
}
Last updated
Was this helpful?