We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
原题链接: https://leetcode.cn/problems/word-pattern/description/
理解题意:
pattern = "abba", s = "dog cat cat cat"
pattern
a
s
dog
cat
pattern = "abba", s = "dog dog dog dog"
b
pattern = "abba", s = "dog constructor constructor dog"
let s2p = {}; console.log(typeof s2p.consructor) // function
consructor
“b”
let s2p = new Map()
解题思路:
pattern -> s
s -> pattern
/** * @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 };
The text was updated successfully, but these errors were encountered:
No branches or pull requests
原题链接:
https://leetcode.cn/problems/word-pattern/description/
理解题意:
pattern = "abba", s = "dog cat cat cat"
,pattern
中的a
同时映射了s
中的dog
和cat
,不正确pattern = "abba", s = "dog dog dog dog"
,s
中的dog
同时映射了pattern
中的a
和b
,不正确pattern = "abba", s = "dog constructor constructor dog"
,如果let s2p = {}; console.log(typeof s2p.consructor) // function
,consructor
无法被映射到“b”
,会导致判断出错,因此只能用let s2p = new Map()
存储映射关系解题思路:
pattern -> s
和s -> pattern
的映射关系The text was updated successfully, but these errors were encountered: