leetcode题目来源:https://leetcode-cn.com/problems/word-pattern/
给定一种规律 pattern 和一个字符串 s ,判断 s 是否遵循相同的规律。
这里的 遵循 指完全匹配,例如, pattern 里的每个字母和字符串 str 中的每个非空单词之间存在着双向连接的对应规律。
Given a pattern and a string s, find if s follows the same pattern.
Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in s.
示例1:
输入: pattern = “abba”, str = “dog cat cat dog”
输出: true
示例 2:
输入:pattern = “abba”, str = “dog cat cat fish”
输出: false
示例 3:
输入: pattern = “aaaa”, str = “dog cat cat dog”
输出: false
Example 1:
Input: pattern = “abba”, s = “dog cat cat dog”
Output: true
Example 2:
Input: pattern = “abba”, s = “dog cat cat fish”
Output: false
Example 3:
Input: pattern = “aaaa”, s = “dog cat cat dog”
Output: false
var wordPattern = function (pattern, s) {
var len = pattern.length, list = s.split(" ")
if (len != list.length) {
console.log("长度不一", len, list.length);
return false
}
var hp = Object.create(null),//定义空对象pattern中的值为键
hs = Object.create(null);//定义空对象list中的值为键
for (let i = 0; i < list.length; i++) {//遍历数组
console.log("hp.has(i)", pattern[i], list[i]);//pattern中第i项;list中的第i项
if (hp[pattern[i]] != void 0) {//pattern[i]键在hp中存在,判断是否相等
if (hp[pattern[i]] != list[i]) {//存在 hp的pattern[i]键值不等于list[i]
console.log("不一致");
return false
}
} else {//不存在就加进去,pattern[i]为键,list[i]为值
hp[pattern[i]] = list[i]
}
if (hs[list[i]] != void 0) {//list[i]键在hs中存在,判断是否相等
if (hs[list[i]] != pattern[i]) {//存在 hs的list[i]键值不等于pattern[i]
console.log("不一致");
return false
}
} else {//不存在就加进去,list[i]为键,pattern[i]为值
hs[list[i]] = pattern[i]
}
}
return true
};
优化代码
var wordPattern = function (pattern, s) {
var len = pattern.length, list = s.split(" ")
if (len != list.length) return false
var hp = Object.create(null),hs = Object.create(null);
for (let i = 0; i < list.length; i++) {
if (hp[pattern[i]] != void 0) {
if (hp[pattern[i]] != list[i]) return false
} else {
hp[pattern[i]] = list[i]
}
if (hs[list[i]] != void 0) {
if (hs[list[i]] != pattern[i]) return false
} else {
hs[list[i]] = pattern[i]
}
}
return true
};
再进行优化代码
var wordPattern = function (pattern, s) {
var len = pattern.length, list = s.split(" ")
if (len != list.length) return false
var hp = Object.create(null),hs = Object.create(null);
for (let i = 0; i < list.length; i++) {
var p=pattern[i],l=list[i]
if (hp[p] != void 0) {
if (hp[p] != l) return false
} else {
hp[p] = l
}
if (hs[l] != void 0) {
if (hs[l] != p) return false
} else {
hs[l] = p
}
}
return true
};