Skip to content

Latest commit

 

History

History
34 lines (30 loc) · 1010 Bytes

2023-02-02.md

File metadata and controls

34 lines (30 loc) · 1010 Bytes

题目

  1. Verifying an Alien Dictionary

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 lexicographically in this alien language.

思路

代码

// runtime 89.29% memory 79.59%
var isAlienSorted = function(words, order) {
  const map = []
  for (let i = 0; i < order.length; i++) {
    map[order.charCodeAt(i) - 97] = i
  }
  function compare(a, b) {
    for (let i = 0; i < Math.min(a.length, b.length); i++) {
      const x = map[a.charCodeAt(i) - 97] - map[b.charCodeAt(i) - 97]
      if (x != 0) {
        return x
      }
    }
    return a.length - b.length
  }
  for (let i = 1; i < words.length; i++) {
    if (compare(words[i-1], words[i]) > 0) {
      return false
    }
  }
  return true
}