Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LeetCode题解:290. 单词规律,哈希表,JavaScript,详细注释 #466

Open
chencl1986 opened this issue Jul 24, 2024 · 0 comments

Comments

@chencl1986
Copy link
Owner

原题链接:
https://leetcode.cn/problems/word-pattern/description/

理解题意:

  1. pattern = "abba", s = "dog cat cat cat"pattern中的a同时映射了s中的dogcat,不正确
  2. pattern = "abba", s = "dog dog dog dog"s中的dog同时映射了pattern中的ab,不正确
  3. pattern = "abba", s = "dog constructor constructor dog",如果let s2p = {}; console.log(typeof s2p.consructor) // functionconsructor无法被映射到“b”,会导致判断出错,因此只能用let s2p = new Map()存储映射关系

解题思路:

  1. 做这题之前,可以先做205. 同构字符串
  2. 用两个Map,分别存储pattern -> ss -> pattern的映射关系
  3. 遍历字符串,查看Map中存储的映射关系是否与遍历到的字符不同,出现不同就表示两个字符串不存在双向连接规律
  4. 如果正常退出循环,表示没意义找到不同的映射关系,两个字符串存在双向连接规律
/**
 * @param {string} pattern
 * @param {string} s
 * @return {boolean}
 */
var wordPattern = function(pattern, s) {
  // 将s按空格切割成数组
  const arr = s.split(' ')
  // 如果pattern和arr的长度不一致,一定没有相同的规律
  if (pattern.length !== arr.length) {
    return false
  }
  // 使用Map存储字符串的映射规律
  // 之所以不用对象,是因为有一个case的s中有constructor
  // 会导致无法映射字符串,而是会映射到constructor函数
  let p2s = new Map()
  let s2p = new Map()

  // 逐个字符对比映射关系
  for (let i = 0; i < pattern.length; i++) {
    // 如果映射关系存在,且与已存储的映射关系不同,表示不存在规律
    if (
      p2s.has(pattern[i]) && (p2s.get(pattern[i]) !== arr[i]) ||
      s2p.has(arr[i]) && (s2p.get(arr[i]) !== pattern[i])
    ) {
      return false
    }

    // 每次循环都缓存当前映射关系
    p2s.set(pattern[i], arr[i])
    s2p.set(arr[i], pattern[i])
  }

  // 如果正常退出循环,表示遵循规律
  return true
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant