LeetCode 953. Verifying an Alien Dictionary

Question

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.

Solution

Actually, the idea is pretty straight forward. We have to see the position of each letter in adjant string and to compare. If there exists less or greater, we can return true or false. Otherwise, we go to the next letter. For the optimization, we can use count sort(mapping first) instead of using Java builtin indexOf.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// time:O(# of words * max(word))
public boolean isAlienSorted(String[] words, String order) {
if (words == null || words.length == 0) return true;
int[] mapping = new int[26];
for (int i = 0; i < 26; i++) {
mapping[order.charAt(i) - 'a'] = i;
}
for (int i = 1; i < words.length; i++) {
if (!isValid(words[i - 1], words[i], mapping)) return false;
}
return true;
}

public boolean isValid(String s, String t, int[] mapping) {
int m = s.length(), n = t.length();
for (int i = 0; i < m && i < n; i++) {
if (s.charAt(i) != t.charAt(i)) {
int idxS = mapping[s.charAt(i) - 'a'];
int idxT = mapping[t.charAt(i) - 'a'];
if (idxS > idxT) return false;
if (idxS < idxT) return true;
}
}
if (m <= n) return true;
return false;
}