-
Notifications
You must be signed in to change notification settings - Fork 0
/
290_WordPattern.js
50 lines (44 loc) · 1.14 KB
/
290_WordPattern.js
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
43
44
45
46
47
48
49
50
// https://leetcode.com/problems/word-pattern/#/description
/**
* @param {string} pattern
* @param {string} str
* @return {boolean}
*/
var wordPattern = function (pattern, str) {
var patternObj = {};
var patternLength = pattern.length;
var strArr = str.split(' ');
var strArrLength = strArr.length;
if (patternLength !== strArrLength) {
return false;
}
var uniqArr = [];
for (var i = 0; i < patternLength; i++) {
var tempPattern = pattern[i];
var word = strArr[i];
if (!patternObj[tempPattern]) {
if (uniqArr.indexOf(word) !== -1) {
return false;
}
uniqArr.push(word);
patternObj[tempPattern] = word;
} else {
if (patternObj[tempPattern] !== word) {
return false;
}
}
}
return true;
};
var pattern = "abba";
var str = "dog cat cat dog";
console.log(wordPattern(pattern, str)); //true
pattern = "abba";
str = "dog cat cat fish";
console.log(wordPattern(pattern, str)); //false
pattern = "aaaa";
str = "dog cat cat dog";
console.log(wordPattern(pattern, str)); //false
pattern = "abba";
str = "dog dog dog dog";
console.log(wordPattern(pattern, str)); //false