Skip to content

953. 验证外星语词典

Posted on:2022年10月26日 at 14:18

953. 验证外星语词典

leetcode 链接

解法一:模拟

Map 存储 order 的顺序,然后依次比较单词顺序。

/**
 * @param {string[]} words
 * @param {string} order
 * @return {boolean}
 */
var isAlienSorted = function (words, order) {
  const orderMap = new Map();
  for (let i = 0; i < order.length; i++) {
    orderMap.set(order[i], i);
  }
  orderMap.set(undefined, -1);
  for (let i = 0; i < words.length - 1; i++) {
    const cur = words[i];
    const next = words[i + 1];
    if (cur === next) {
      continue;
    }
    let k = 0;
    while (true) {
      if (orderMap.get(cur[k]) < orderMap.get(next[k])) {
        break;
      } else if (orderMap.get(cur[k]) > orderMap.get(next[k])) {
        return false;
      } else {
        k++;
      }
    }
  }
  return true;
};