forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Verifying an Alien Dictionary.java
32 lines (29 loc) · 1.19 KB
/
Verifying an Alien Dictionary.java
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
27
28
29
30
31
32
class Solution {
public boolean isAlienSorted(String[] words, String order) {
int val=1;
int[] alp = new int[26];
for(int i=0;i<order.length();i++) {
alp[order.charAt(i)-'a']=val;
val++;
}
int flag=0; // if second string is shorter than first then this will be used to check if second is a subset of first starting from the beginning
for(int i=0;i<words.length-1;i++) {
flag=0;
for(int j=0; j<words[i].length() && j<words[i+1].length(); j++) {
if(words[i].charAt(j) == words[i+1].charAt(j)) {
continue;
}
if(alp[words[i].charAt(j)-'a'] > alp[words[i+1].charAt(j)-'a']) {
return false;
} else if(alp[words[i].charAt(j)-'a'] < alp[words[i+1].charAt(j)-'a']) {
flag=1;
break;
}
}
if(flag==0 && words[i].length()>words[i+1].length()) {
return false; // if second word is sub string of first word starting from the beginning, return false.
}
}
return true;
}
}