https://leetcode.com/problems/word-pattern/
Solution 1
/**
* @param {string} pattern
* @param {string} s
* @return {boolean}
*/
var wordPattern = function (pattern, s) {
const splitS = s.split(' ');
if (splitS.length !== pattern.length) {
return false;
}
if (new Set(pattern.split('')).size !== new Set(splitS).size) {
return false;
}
const hashMap = {};
for (let i = 0; i < pattern.length; i++) {
if (hashMap[pattern[i]]) {
if (hashMap[pattern[i]] !== splitS[i]) {
return false;
}
} else {
hashMap[pattern[i]] = splitS[i];
}
}
return true;
};