-
Notifications
You must be signed in to change notification settings - Fork 0
/
WordPattern.js
60 lines (52 loc) · 1.42 KB
/
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
51
52
53
54
55
56
57
58
59
60
var wordPattern = function(pattern, s) {
const arrayPattern = pattern.split("");
const arrayS = s.split(" ");
if (arrayPattern.length !== arrayS.length) {
return false;
}
const map = new Map();
for (let i = 0; i < arrayPattern.length; i++) {
const char = arrayPattern[i];
const word = arrayS[i];
if (map.has(char)) {
if (map.get(char) !== word) {
return false;
}
} else {
if (Array.from(map.values()).includes(word)) {
return false;
}
map.set(char, word);
}
}
return true;
};
const pattern = "abba";
const s = "dog cat cat dog";
console.log(wordPattern(pattern, s)); // Output: true
//using object
const wordPatternObject = (pattern, s)=> {
const arrayPattern = pattern.split("");
const arrayS = s.split(" ");
if (arrayPattern.length !== arrayS.length) {
return false;
}
const result ={}
for (let i = 0; i < arrayPattern.length; i++) {
const char = arrayPattern[i];
const word = arrayS[i];
if (result[char]) {
if (result[char] !== word) {
return false;
}
} else {
if(Object.values(result).includes(word))
return false;
}
map.set(char, word);
}
return true;
}
const patterns = "abba";
const ss = "dog cat cat dog";
console.log(wordPattern(patterns, ss))