Skip to content

Commit

Permalink
290. 单词规律.
Browse files Browse the repository at this point in the history
  • Loading branch information
yoozo committed Dec 16, 2020
1 parent 1b86abd commit 956f886
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions lib/290_wordPattern.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// 290. 单词规律.
// https://leetcode-cn.com/problems/word-pattern/

/**
* @param {string} pattern
* @param {string} s
* @return {boolean}
*/
var wordPattern = function (pattern, s) {
const pMap = new Map()
for (let i = 0; i < pattern.length; i++) {
const c = pattern[i]
if (pMap.has(c)) {
pMap.get(c).push(i)
} else {
pMap.set(c, [i])
}
}
const sArray = s.split(' ')
if (pattern.length !== sArray.length) {
return false
}
const word = []
for (const item of pMap) {
if (!word.includes(sArray[item[1][0]])) {
word.push(sArray[item[1][0]])
} else {
return false
}
for (let i = 1; i < item[1].length; i++) {
if (sArray[item[1][0]] !== sArray[item[1][i]]) {
return false
}
}
}
return true
};


console.log(wordPattern("abba", "dog dd dd dog"))

0 comments on commit 956f886

Please sign in to comment.