Problem
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.
Examples
Example 1:
| |
Example 2:
| |
Example 3:
| |
Notes
You may assume both pattern and str contains only lowercase letters.
This is a follow up of Word Pattern 1.
Solution
Method 1 - Backtracking with 2 Hashmaps 🏆
We can use 2 hashmaps:
- Use a HashMap to map characters in the pattern to substrings in
s. - Use another HashMap to ensure the mapping is bijective.
- Use recursion to explore mappings until the entire pattern and string have been matched or a mismatch is detected.
We will have following cases in backtracking:
- If both the pattern and string are fully matched, return
true. - If either the pattern or the string is fully matched but the other is not, return
false. - Ensure proper backtracking by removing the mapping when a mismatch occurs.
For edge case, don’t forget below part during DFS.
| |
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(n^m)wherenis the length of the string andmis the length of the pattern. - 🧺 Space complexity:
O(m + n)for storing the mappings and recursive call stack.