leetcode 953. 验证外星语词典

题解

依次比较words中连续的两个单词,前一个单词的字典序大于后一个时返回false

示例代码(go)

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
func isAlienSorted(words []string, order string) bool {
for i := 1; i < len(words); i++ {
if compare(words[i-1], words[i], order) == 1 {
return false
}
}
return true
}

func compare(a string, b string, order string) int {
la, lb := len(a), len(b)
for i, j := 0, 0; i < la && j < lb; {
if strings.Index(order, string(a[i])) > strings.Index(order, string(b[j])) {
return 1
}
if strings.Index(order, string(a[i])) < strings.Index(order, string(b[j])) {
return -1
}
i++
j++
}
if la > lb {
return 1
} else if la < lb {
return -1
}
return 0
}