Word Pattern Problem
Description
LeetCode Problem 290.
Given a pattern and a string s, find if sfollows 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:
Input: pattern = "abba", s = "dog cat cat dog"
Output: true
Example 2:
Input: pattern = "abba", s = "dog cat cat fish"
Output: false
Example 3:
Input: pattern = "aaaa", s = "dog cat cat dog"
Output: false
Example 4:
Input: pattern = "abba", s = "dog dog dog dog"
Output: false
Constraints:
- 1 <= pattern.length <= 300
- pattern contains only lower-case English letters.
- 1 <= s.length <= 3000
- s contains only lower-case English letters and spaces ' '.
- s does not contain any leading or trailing spaces.
- All the words in s are separated by a single space.
Solution
Approach: Two Hash Maps
A bijection means two things: each letter always stands for the same word, and no two letters stand for the same word. One map checks the first, a second map checks the other direction.
- Split
son spaces. If the number of words differs from the length ofpattern, they cannot match. - Walk the letters and words side by side, with
wordOf(letter to word) andletterOf(word to letter):- If
letteris already mapped to a different word, returnfalse. - If
wordis already mapped to a different letter, returnfalse. - Otherwise record both directions.
- If
- If the walk finishes, return
true.
Checking only one direction is the usual mistake: with just wordOf, pattern = "abba" and s = "dog dog dog dog" would pass, because a and b are each consistent on their own, yet both stand for "dog". Example 4 is exactly this case.
Complexity: O(n + m) time and O(n + m) space, where n is the length of pattern and m the length of s.
class Solution:
def wordPattern(self, pattern: str, s: str) -> bool:
words = s.split(" ")
if len(words) != len(pattern):
return False
word_of = {} # letter -> the word it stands for
letter_of = {} # word -> the letter that stands for it
for letter, word in zip(pattern, words):
if letter in word_of and word_of[letter] != word:
return False # the letter already stands for another word
if word in letter_of and letter_of[word] != letter:
return False # the word already belongs to another letter
word_of[letter] = word
letter_of[word] = letter
return True