-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0290-word-pattern.js
More file actions
42 lines (36 loc) · 1.31 KB
/
0290-word-pattern.js
File metadata and controls
42 lines (36 loc) · 1.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
* Word Pattern
* Time Complexity: O(M)
* Space Complexity: O(M)
*/
var wordPattern = function (pattern, s) {
const stringWords = s.split(' ');
const patternLength = pattern.length;
const stringWordCount = stringWords.length;
if (patternLength !== stringWordCount) {
return false;
}
const patternCharacterToWordMap = new Map();
const wordToStringCharacterMap = new Map();
for (let charIndex = 0; charIndex < patternLength; charIndex++) {
const currentPatternChar = pattern[charIndex];
const currentStringWord = stringWords[charIndex];
if (patternCharacterToWordMap.has(currentPatternChar)) {
const mappedWord = patternCharacterToWordMap.get(currentPatternChar);
if (mappedWord !== currentStringWord) {
return false;
}
} else {
patternCharacterToWordMap.set(currentPatternChar, currentStringWord);
}
if (wordToStringCharacterMap.has(currentStringWord)) {
const mappedCharacter = wordToStringCharacterMap.get(currentStringWord);
if (mappedCharacter !== currentPatternChar) {
return false;
}
} else {
wordToStringCharacterMap.set(currentStringWord, currentPatternChar);
}
}
return true;
};