-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathVerifyTheAlienDictionary.java
85 lines (53 loc) · 2.37 KB
/
VerifyTheAlienDictionary.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
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
package other;
/**
* @Author: Wenhang Chen
* @Description:某种外星语也使用英文小写字母,但可能顺序 order 不同。字母表的顺序(order)是一些小写字母的排列。
* <p>
* 给定一组用外星语书写的单词 words,以及其字母表的顺序 order,只有当给定的单词在这种外星语中按字典序排列时,返回 true;否则,返回 false。
* <p>
*
* <p>
* 示例 1:
* <p>
* 输入:words = ["hello","leetcode"], order = "hlabcdefgijkmnopqrstuvwxyz"
* 输出:true
* 解释:在该语言的字母表中,'h' 位于 'l' 之前,所以单词序列是按字典序排列的。
* 示例 2:
* <p>
* 输入:words = ["word","world","row"], order = "worldabcefghijkmnpqstuvxyz"
* 输出:false
* 解释:在该语言的字母表中,'d' 位于 'l' 之后,那么 words[0] > words[1],因此单词序列不是按字典序排列的。
* 示例 3:
* <p>
* 输入:words = ["apple","app"], order = "abcdefghijklmnopqrstuvwxyz"
* 输出:false
* 解释:当前三个字符 "app" 匹配时,第二个字符串相对短一些,然后根据词典编纂规则 "apple" > "app",因为 'l' > '∅',其中 '∅' 是空白字符,定义为比任何其他字符都小(更多信息)。
* @Date: Created in 8:30 7/1/2020
* @Modified by:
*/
public class VerifyTheAlienDictionary {
public boolean isAlienSorted(String[] words, String order) {
int[] index = new int[26];
for (int i = 0; i < order.length(); ++i)
index[order.charAt(i) - 'a'] = i;
search:
for (int i = 0; i < words.length - 1; ++i) {
String word1 = words[i];
String word2 = words[i + 1];
// Find the first difference word1[k] != word2[k].
for (int k = 0; k < Math.min(word1.length(), word2.length()); ++k) {
if (word1.charAt(k) != word2.charAt(k)) {
// If they compare badly, it's not sorted.
if (index[word1.charAt(k) - 'a'] > index[word2.charAt(k) - 'a'])
return false;
continue search;
}
}
// If we didn't find a first difference, the
// words are like ("app", "apple").
if (word1.length() > word2.length())
return false;
}
return true;
}
}