0%

953. Verifying an Alien Dictionary

O(m*n) time O(1) space where m is the avg length of a word while n is the number of words

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
bool isAlienSorted(vector<string>& words, string order) {
int dict[26] = {0};
for (int i = 0; i < 26; ++i) {
dict[order[i] - 'a'] = i;
}
for (int i = 1; i < words.size(); ++i) {
if (!lte(words[i - 1], words[i], dict)) return false;
}
return true;
}

bool lte(const string &a, const string &b, int dict[26]) {
int m = a.length(), n = b.length();
for (int i = 0; i < min(m, n); ++i) {
if (a[i] == b[i]) continue;
return dict[a[i] - 'a'] <= dict[b[i] - 'a'];
}
return m <= n;
}
};