Skip to content

Commit 15e6f2a

Browse files
committed
Add solution #290
1 parent 4790837 commit 15e6f2a

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

0290-word-pattern.js

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* 290. Word Pattern
3+
* https://leetcode.com/problems/word-pattern/
4+
* Difficulty: Easy
5+
*
6+
* Given a pattern and a string s, find if s follows the same pattern.
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.
10+
*/
11+
12+
/**
13+
* @param {string} pattern
14+
* @param {string} s
15+
* @return {boolean}
16+
*/
17+
var wordPattern = function(pattern, s) {
18+
const words = s.split(/\s+/);
19+
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+
});
29+
};

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,7 @@
113113
273|[Integer to English Words](./0273-integer-to-english-words.js)|Hard|
114114
278|[First Bad Version](./0278-first-bad-version.js)|Medium|
115115
283|[Move Zeroes](./0283-move-zeroes.js)|Easy|
116+
290|[Word Pattern](./0290-word-pattern.js)|Easy|
116117
326|[Power of Three](./0326-power-of-three.js)|Easy|
117118
342|[Power of Four](./0342-power-of-four.js)|Easy|
118119
344|[Reverse String](./0344-reverse-string.js)|Easy|
@@ -285,4 +286,4 @@
285286

286287
[MIT License](https://opensource.org/licenses/MIT)
287288

288-
Copyright (c) 2019-2022 [Josh Crozier](https://joshcrozier.com)
289+
Copyright (c) 2019-2023 [Josh Crozier](https://joshcrozier.com)

0 commit comments

Comments
 (0)