LeetCode: Word Pattern Solution
2 hash tablesApproach
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(" ")45 if (pattern.length !== s.length) return false67 const patternWordMap = new Map()8 const wordMapped = new Set()910 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 continue15 }1617 if (patternWordMap.get(pattern[i]) !== s[i]) return false18 }1920 return true21}
References
Similar problems
Word Pattern II
Comments
Loading comments...
Tags
leetcode
hash table
string
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.
Next Post
LeetCode: Power of Four
School math
Previous Post
LeetCode: Symmetric Tree
Recursion