外星语言是否排序

76 阅读1分钟

image.png

代码:

  1. index 数组按照指定的字典序给字符带上权重
  2. next————continue next,使带有 next 标签的 for 执行 continue
  3. 第一层 for 负责遍历第几个字符串
  4. 第二层 for 负责字符串中的字符比较
  5. 如果第二层 for 比较完了还没有结果,则比较长度
func isAlienSorted(words []string, order string) bool {
    index := [26]int{}
    for i, c := range order {
        index[c-'a'] = i
    }
next:
    for i := 1; i < len(words); i++ {
        for j := 0; j < len(words[i-1]) && j < len(words[i]); j++ {
            pre, cur := index[words[i-1][j]-'a'], index[words[i][j]-'a']
            if pre > cur {
                return false
            }
            if pre < cur {
                continue next
            }
        }
        if len(words[i-1]) > len(words[i]) {
            return false
        }
    }
    return true
}