|
| 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