290. 单词规律
题
思路
"abba","dog cat cat dog"
=> true
使用hashmap去比对,判断是否有不一致的value
"abba","dog dog dog dog"
=> false
再生成反向的hashmap去判断是否一致
代码
function wordPattern(pattern: string, s: string): boolean {
const words = s.split(" ");
const len = pattern.length;
if(words.length !== len) return false;
const map = new Map();
const rMap = new Map();
for(let i = 0; i < len; i++) {
if(map.has(pattern[i]) && map.get(pattern[i]) !== words[i]) return false;
map.set(pattern[i], words[i]);
rMap.set(words[i], pattern[i]);
}
return map.size === rMap.size;
};
评论