1
class Solution {
2
public boolean isAlienSorted(String[] words, String order) {
3
int val = 1;
4
int[] alp = new int[26];
5

6
for (int i = 0; i < order.length(); i++) {
7
alp[order.charAt(i) - 'a'] = val;
8
val++;
9
}
10
int flag =
11
0; // if second string is shorter than first then this will be used to check if second is a
12
// subset of first starting from the beginning
13

14
for (int i = 0; i < words.length - 1; i++) {
15
flag = 0;
16
for (int j = 0; j < words[i].length() && j < words[i + 1].length(); j++) {
17
if (words[i].charAt(j) == words[i + 1].charAt(j)) {
18
continue;
19
}
20
if (alp[words[i].charAt(j) - 'a'] > alp[words[i + 1].charAt(j) - 'a']) {
21
return false;
22
} else if (alp[words[i].charAt(j) - 'a'] < alp[words[i + 1].charAt(j) - 'a']) {
23
flag = 1;
24
break;
25
}
26
}
27
if (flag == 0 && words[i].length() > words[i + 1].length()) {
28
return false; // if second word is sub string of first word starting from the beginning,
29
// return false.
30
}
31
}
32

33
return true;
34
}
35
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0