Skip to content

Commit c8bbb44

Browse files
committed
Add solution #290
1 parent 85fc8b2 commit c8bbb44

File tree

1 file changed

+12
-12
lines changed

1 file changed

+12
-12
lines changed

solutions/0290-word-pattern.js

+12-12
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,11 @@
55
*
66
* Given a pattern and a string s, find if s follows the same pattern.
77
*
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.
1013
*/
1114

1215
/**
@@ -15,15 +18,12 @@
1518
* @return {boolean}
1619
*/
1720
var wordPattern = function(pattern, s) {
18-
const words = s.split(/\s+/);
21+
const words = s.split(' ');
22+
if (pattern.length !== words.length) return false;
1923
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+
);
2929
};

0 commit comments

Comments
 (0)