-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy path0291-word-pattern-ii.js
More file actions
51 lines (42 loc) · 1.5 KB
/
0291-word-pattern-ii.js
File metadata and controls
51 lines (42 loc) · 1.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/**
* 291. Word Pattern II
* https://leetcode.com/problems/word-pattern-ii/
* Difficulty: Medium
*
* Given a pattern and a string s, return true if s matches the pattern.
*
* A string s matches a pattern if there is some bijective mapping of single characters to
* non-empty strings such that if each character in pattern is replaced by the string it
* maps to, then the resulting string is s. A bijective mapping means that no two characters
* map to the same string, and no character maps to two different strings.
*/
/**
* @param {string} pattern
* @param {string} s
* @return {boolean}
*/
var wordPatternMatch = function(pattern, s) {
const charToWord = new Map();
const usedWords = new Set();
return backtrack(0, 0);
function backtrack(patIndex, strIndex) {
if (patIndex === pattern.length && strIndex === s.length) return true;
if (patIndex >= pattern.length || strIndex >= s.length) return false;
const char = pattern[patIndex];
if (charToWord.has(char)) {
const word = charToWord.get(char);
if (!s.startsWith(word, strIndex)) return false;
return backtrack(patIndex + 1, strIndex + word.length);
}
for (let i = strIndex + 1; i <= s.length; i++) {
const word = s.slice(strIndex, i);
if (usedWords.has(word)) continue;
charToWord.set(char, word);
usedWords.add(word);
if (backtrack(patIndex + 1, strIndex + word.length)) return true;
charToWord.delete(char);
usedWords.delete(word);
}
return false;
}
};