Word Pattern II - 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
- No character maps to two different strings
Input & Output
Example 1 — Basic Pattern Match
$
Input:
pattern = "abab", s = "redblueredblue"
›
Output:
true
💡 Note:
One possible mapping: a → 'red', b → 'blue'. This creates 'red' + 'blue' + 'red' + 'blue' = 'redblueredblue'
Example 2 — No Valid Mapping
$
Input:
pattern = "aaaa", s = "asdasdasdasd"
›
Output:
true
💡 Note:
Pattern 'aaaa' can map a → 'asd' to create 'asd' + 'asd' + 'asd' + 'asd' = 'asdasdasdasd'
Example 3 — Bijection Violation
$
Input:
pattern = "abab", s = "asdfhjkl"
›
Output:
false
💡 Note:
No bijective mapping exists. For example, trying a → 'as', b → 'df' gives 'as' + 'df' + 'as' + 'df' = 'asdfasdf' ≠ 'asdfhjkl'. All other possible mappings also fail to produce the target string.
Constraints
- 1 ≤ pattern.length ≤ 20
- 1 ≤ s.length ≤ 50
- pattern contains only lowercase English letters
- s contains only lowercase English letters
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code