-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathVerifyingAnAlienDictionary.java
More file actions
86 lines (72 loc) · 2.97 KB
/
Copy pathVerifyingAnAlienDictionary.java
File metadata and controls
86 lines (72 loc) · 2.97 KB
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
// 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.
// See: https://leetcode.com/problems/verifying-an-alien-dictionary/
package leetcode.string;
import java.util.HashMap;
import java.util.Map;
public class VerifyingAnAlienDictionary {
/**
* Array solution.
* Note that even small and simple dictionary the array implementation is much faster than the HashMap.
*/
public boolean isAlienSorted(String[] words, String order) {
int[] mapper = new int[26];
for (int i = 0; i < order.length(); i++)
mapper[order.charAt(i) - 'a'] = i;
boolean res = false;
for (int i = 0; i < words.length - 1; i++) {
String w1 = words[i];
String w2 = words[i + 1];
int len = Math.min(w1.length(), w2.length());
for (int j = 0; j < len; j++) {
if (mapper[w1.charAt(j) - 'a'] < mapper[w2.charAt(j) - 'a']) {
res = true;
break;
}
else if (mapper[w1.charAt(j) - 'a'] > mapper[w2.charAt(j) - 'a'])
return false;
}
if (!res && w1.length() > w2.length()) {
return false;
}
}
return res;
}
/**
* HashMap implementation.
*/
public boolean isAlienSorted_var1(String[] words, String order) {
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < order.length(); i++)
map.put(order.charAt(i), i);
boolean res = false;
for (int i = 0; i < words.length - 1; i++) {
String w1 = words[i];
String w2 = words[i + 1];
int len = Math.min(w1.length(), w2.length());
for (int j = 0; j < len; j++) {
if (map.get(w1.charAt(j)) < map.get(w2.charAt(j))) {
res = true;
break;
}
else if (map.get(w1.charAt(j)) > map.get(w2.charAt(j)))
return false;
}
if (!res && w1.length() > w2.length()) {
return false;
}
}
return res;
}
public static void main(String[] args) {
VerifyingAnAlienDictionary sln = new VerifyingAnAlienDictionary();
System.out.println(sln.isAlienSorted(new String[] { "hello", "leetcode" },
"hlabcdefgijkmnopqrstuvwxyz"));
System.out.println(sln.isAlienSorted(new String[] { "word", "world", "row" },
"worldabcefghijkmnpqstuvxyz"));
System.out.println(sln.isAlienSorted(new String[] { "kuvp", "q" },
"ngxlkthsjuoqcpavbfdermiywz"));
}
}