Skip to content

Commit da456a3

Browse files
committed
Add solution #291
1 parent 74c3819 commit da456a3

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -279,6 +279,7 @@
279279
288|[Unique Word Abbreviation](./solutions/0288-unique-word-abbreviation.js)|Medium|
280280
289|[Game of Life](./solutions/0289-game-of-life.js)|Medium|
281281
290|[Word Pattern](./solutions/0290-word-pattern.js)|Easy|
282+
291|[Word Pattern II](./solutions/0291-word-pattern-ii.js)|Medium|
282283
292|[Nim Game](./solutions/0292-nim-game.js)|Easy|
283284
295|[Find Median from Data Stream](./solutions/0295-find-median-from-data-stream.js)|Hard|
284285
297|[Serialize and Deserialize Binary Tree](./solutions/0297-serialize-and-deserialize-binary-tree.js)|Hard|

solutions/0291-word-pattern-ii.js

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

0 commit comments

Comments
 (0)