290. Word Pattern ๐งฉ
Difficulty: Easy
- Tags: Hash Table
, String
Problem Statement ๐
Given a pattern
and a string s
, find if s
follows 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
.
Examples ๐
๐น Example 1:
Input:
Output:
๐น Example 2:
Input:
Output:
๐น Example 3:
Input:
Output:
Constraints โ๏ธ
1 <= pattern.length <= 300
pattern
contains only lower-case English letters.1 <= s.length <= 3000
s
contains only lowercase 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 ๐ก
To determine if s
follows the same pattern, we need to ensure that there is a one-to-one correspondence between the characters of pattern
and the words in s
. We can use two hash maps for this purpose:
One map to store the pattern's character to word mapping.
Another map to store the word to pattern's character mapping.
Java Solution
Explanation of the Solution
Splitting the Input String:
We split
s
by spaces to get an array of words.
Checking Lengths:
If the length of
pattern
doesn't match the number of words ins
, returnfalse
.
Mapping Characters to Words:
We use two hash maps:
patternToWord
to map characters inpattern
to words ins
.wordToPattern
to map words ins
to characters inpattern
.
Validation:
For each character and corresponding word, we check if the current mapping exists.
If it exists and doesn't match the expected value, return
false
.If a valid mapping exists, continue checking until all characters and words are validated.
Return True:
If all the mappings are consistent, return
true
.
Time Complexity โณ
O(n):
n
is the length of the pattern (or the number of words ins
).Each character and word is processed once.
Space Complexity ๐พ
O(n):
Space is used for two hash maps, each storing up to
n
entries.
You can find the full solution here.
Last updated