Leetcode 290 - Word pattern

Note:

  • Because it’s bijection, we have to use two maps.
  • One map is not enough for cases like 'abba', 'dog dog dog dog'

Question:

Given a pattern and a string s, find if s 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 s.

Example:

1
2
Input: pattern = "abba", s = "dog cat cat dog"
Output: true

Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* @param {string} pattern
* @param {string} s
* @return {boolean}
*/
var wordPattern = function(pattern, s) {
s = s.split(' ');
if (s.length !== pattern.length) return false;
let pMap = new Map();
let sMap = new Map();
for (let i = 0; i < s.length; i++) {
if (pMap.has(pattern[i]) && pMap.get(pattern[i]) !== s[i] || sMap.has(s[i]) && sMap.get(s[i]) !== pattern[i]) return false;
pMap.set(pattern[i], s[i]);
sMap.set(s[i], pattern[i]);
}
return true;
};