-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path290_Word_Pattern.js
More file actions
34 lines (28 loc) · 1.2 KB
/
290_Word_Pattern.js
File metadata and controls
34 lines (28 loc) · 1.2 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
// LeetCode 290. Word Pattern
// Given a pattern and a string str, find if str follows the same pattern.
// Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.
// Examples: pattern = "abba", str = "dog cat cat dog" should return true. pattern = "abba", str = "dog cat cat fish" should return false. pattern = "aaaa", str = "dog cat cat dog" should return false. pattern = "abba", str = "dog dog dog dog" should return false. Notes: You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.
function wordPattern(pattern, str) {
var patternMap = {};
var strMap = {};
var ary = str.split(/\s/);
if ((pattern.length != str.split(/\s/).length)) {
return false;
}
for (var i in pattern) {
var p = pattern[i];
var s = ary[i];
if (!patternMap[p]) {
patternMap[p] = s;
} else if (patternMap[p] != s) {
return false;
}
if (!strMap[s]) {
strMap[s] = p;
} else if (strMap[s] != p) {
return false;
}
}
return true;
}
wordPattern("abba", "dog cat cat dog");