LeetCode: Word Pattern Solution

2 hash tables

Approach

One hash table to map pattern to word

One hash table to check if word is already mapped by a pattern

Implementation

1var wordPattern = function (pattern, s) {
2 pattern = pattern.split("")
3 s = s.split(" ")
4
5 if (pattern.length !== s.length) return false
6
7 const patternWordMap = new Map()
8 const wordMapped = new Set()
9
10 for (let i = 0; i < pattern.length; i++) {
11 if (!patternWordMap.has(pattern[i]) && !wordMapped.has(s[i])) {
12 patternWordMap.set(pattern[i], s[i])
13 wordMapped.add(s[i])
14 continue
15 }
16
17 if (patternWordMap.get(pattern[i]) !== s[i]) return false
18 }
19
20 return true
21}

References

Original problem

Similar problems

Isomorphic Strings

Word Pattern II

Comments

Loading comments...

Tags

leetcode

hash table

string

Next Post

LeetCode: Power of Four

School math

Previous Post

HoningJS

Search Posts