我的js算法爬坑之旅-单词规律

78 阅读1分钟

第七十天:力扣290题,单词规律

地址:leetcode-cn.com/problems/wo…

思路:map和哈希。

function wordPattern(pattern: string, s: string): boolean {
  const p:Array<string> = pattern.split('');// 转成数组
  const sw:Array<string> = s.split(' ');// 转成数组
  if(p.length !== sw.length)// 长度不一,直接false
  {
    return false;
  }
  const ps:Set<string> = new Set(p);// Set一下,下面判断种类数是否一样
  const sws:Set<string> = new Set(sw);
  if(ps.size !== sws.size)// 排除种类数不一样的情况
  {
    return false;
  }
  let map:Map<string,string> = new Map();// map进行存储键值对
  for(let i:number = 0; i < p.length; i++ )
  {
    if(map.has(p[i]) && map.get(p[i]) !== sw[i])// 判断
    {
      return false;
    }
    map.set(p[i], sw[i]);
  }
  return true;
};

执行用时:76 ms, 在所有 TypeScript 提交中击败了94.44%的用户

内存消耗:40.2 MB, 在所有 TypeScript 提交中击败了33.33%的用户