Determine whether a pattern string can be matched to words in a sentence with a one-to-one mapping.
Given a pattern consisting of lowercase letters and a sentence made of space-separated words, determine whether the sentence follows the same pattern.
A valid match means each pattern character maps to exactly one word, and each word maps back to exactly one pattern character. In other words, the mapping must be a bijection.
Input Format
- A string
pattern - A string
scontaining words separated by single spaces
Output Format
- Return
trueifsfollowspattern - Otherwise return
false
Constraints
1 <= pattern.length <= 300patterncontains only lowercase English letters1 <= s.length <= 3000scontains lowercase English letters and single spaces- Words are separated by exactly one space
Example 1
Input
pattern = "abba" s = "dog cat cat dog"
Output
true
Explanation
a -> dog and b -> cat forms a consistent one-to-one mapping.
Example 2
Input
pattern = "abba" s = "dog cat cat fish"
Output
false
Explanation
The last character a would need to map to both dog and fish, which is not allowed.
Show 1 more example
Example 3
Input
pattern = "aaaa" s = "dog cat cat dog"
Output
false
Explanation
The single character a would have to map to multiple different words.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.