|
5 | 5 | *
|
6 | 6 | * Given a pattern and a string s, find if s follows the same pattern.
|
7 | 7 | *
|
8 |
| - * Here follow means a full match, such that there is a bijection between |
9 |
| - * a letter in pattern and a non-empty word in s. |
| 8 | + * Here follow means a full match, such that there is a bijection between a letter in |
| 9 | + * pattern and a non-empty word in s. Specifically: |
| 10 | + * - Each letter in pattern maps to exactly one unique word in s. |
| 11 | + * - Each unique word in s maps to exactly one letter in pattern. |
| 12 | + * - No two letters map to the same word, and no two words map to the same letter. |
10 | 13 | */
|
11 | 14 |
|
12 | 15 | /**
|
|
15 | 18 | * @return {boolean}
|
16 | 19 | */
|
17 | 20 | var wordPattern = function(pattern, s) {
|
18 |
| - const words = s.split(/\s+/); |
| 21 | + const words = s.split(' '); |
| 22 | + if (pattern.length !== words.length) return false; |
19 | 23 | const map = new Map();
|
20 |
| - |
21 |
| - return words.every((word, index) => { |
22 |
| - const offset = pattern.length === words.length ? index + 1 : words.length / pattern.length; |
23 |
| - const sequence = pattern.slice(index, offset); |
24 |
| - if (!map.has(sequence) && !Array.from(map.values()).includes(word)) { |
25 |
| - map.set(sequence, word); |
26 |
| - } |
27 |
| - return map.get(sequence) === word && pattern.length <= words.length; |
28 |
| - }); |
| 24 | + return pattern.split('').every((char, i) => |
| 25 | + map.has(char) |
| 26 | + ? map.get(char) === words[i] |
| 27 | + : !([...map.values()].includes(words[i])) && map.set(char, words[i]) |
| 28 | + ); |
29 | 29 | };
|
0 commit comments