Word Pattern II Problem
Description
LeetCode Problem 291.
Given a pattern and a string s, return true if s matches the pattern.
A string s matches a pattern if there is some bijective mapping of single characters to non-empty strings such that if each character in pattern is replaced by the string it maps to, then the resulting string is s. A bijective mapping means that no two characters map to the same string, and no character maps to two different strings.
Example 1:
Input: pattern = "abab", s = "redblueredblue"
Output: true
Explanation: One possible mapping is as follows:
'a' -> "red"
'b' -> "blue"
Example 2:
Input: pattern = "aaaa", s = "asdasdasdasd"
Output: true
Explanation: One possible mapping is as follows:
'a' -> "asd"
Example 3:
Input: pattern = "aabb", s = "xyzabcxzyabc"
Output: false
Constraints:
1 <= pattern.length, s.length <= 20patternandsconsist of only lowercase English letters.
Solution
Approach: Backtracking with a Two-Way Mapping
Unlike Word Pattern, the words are not separated by spaces, so we do not know where each piece of s ends. With both strings at most 20 characters long, we can try the possibilities with backtracking.
match(i, j) answers: can pattern[i:] match s[j:], given the choices made so far? Let c = pattern[i].
- If
calready maps to a stringt, thensmust continue withtat positionj. If it does, continue withmatch(i + 1, j + len(t)); otherwise this branch fails. - If
chas no mapping yet, try every non-empty piecet = s[j:k]. Skip pieces that another character already uses, because the mapping must be one-to-one. Assignc -> t, recurse withmatch(i + 1, k), and if that fails, undo the assignment and try a longer piece.
It succeeds when both strings run out at the same time. Two details keep it correct and fast:
- The
usedset is what makes the mapping a bijection. Without it,pattern = "ab", s = "aa"would wrongly match witha -> "a"andb -> "a". - Every remaining pattern character needs at least one letter, so when
shas fewer letters left than the pattern has characters, stop early.
Complexity: exponential in the worst case: roughly O(nm) choices for a pattern of length m and a string of length n, each checked in O(n). The small limits keep it fast. O(m + n) space for the recursion and the mapping.
class Solution:
def wordPatternMatch(self, pattern: str, s: str) -> bool:
m, n = len(pattern), len(s)
mapping = {} # pattern character -> the substring it stands for
used = set() # substrings already taken by some character (the mapping is one-to-one)
def match(i: int, j: int) -> bool:
"""Can pattern[i:] match s[j:] under the current mapping?"""
if i == m or j == n:
return i == m and j == n
if n - j < m - i:
return False # every remaining character needs at least one letter
c = pattern[i]
if c in mapping:
t = mapping[c]
return s.startswith(t, j) and match(i + 1, j + len(t))
for k in range(j + 1, n + 1): # try every non-empty s[j:k] for c
t = s[j:k]
if t in used:
continue
mapping[c] = t
used.add(t)
if match(i + 1, k):
return True
del mapping[c] # undo and try a longer piece
used.remove(t)
return False
return match(0, 0)