Skip to content

Commit 521b1b6

Browse files
authored
Update 291-word-pattern-ii.js
1 parent 1361498 commit 521b1b6

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

291-word-pattern-ii.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,3 +28,41 @@ function isMatch(str, i, pat, j, map, set) {
2828
}
2929
return false
3030
}
31+
32+
// another
33+
34+
/**
35+
* @param {string} pattern
36+
* @param {string} s
37+
* @return {boolean}
38+
*/
39+
const wordPatternMatch = function(pattern, s) {
40+
const obj = { res: false }
41+
const hash = {}
42+
helper(pattern, s, 0, 0, hash, obj)
43+
return obj.res
44+
};
45+
46+
function helper(p, s, i, j, hash, obj) {
47+
if(obj.res) return
48+
if(i === p.length && j === s.length) {
49+
obj.res = true
50+
return
51+
}
52+
if(i >= p.length || j >= s.length) return
53+
for(let m = j; m < s.length && obj.res === false; m++) {
54+
const tmp = s.slice(j, m + 1)
55+
if(hash[p[i]]) {
56+
if(tmp === hash[p[i]]) {
57+
helper(p, s, i + 1, m + 1, hash, obj)
58+
}
59+
} else {
60+
const set = new Set(Object.values(hash))
61+
if (!set.has(tmp)) {
62+
hash[p[i]] = tmp
63+
helper(p, s, i + 1, m + 1, hash, obj)
64+
delete hash[p[i]]
65+
}
66+
}
67+
}
68+
}

0 commit comments

Comments
 (0)