思路:
建立两个哈希表,分别保存:
1 模式 :单词
2 单词 :是否出现过
水题
/**
* @param {string} pattern
* @param {string} str
* @return {boolean}
*/
var wordPattern = function(pattern, str) {
var pats = pattern.split('');
var words = str.split(' ');
if (pats.length !== words.length) return false;
var map = {}; // p : word
var wordMap = {}; // word : bool
for (let i = 0; i < pats.length; i++) {
var p = pats[i];
var s = words[i];
if (!wordMap[s] && !map[p]) {
map[p] = s;
wordMap[s] = true;
} else if (map[p] !== s) {
return false;
}
}
return true;
};