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.
Example 1:
Input: pattern = "abba", s = "dog cat cat dog"
Output: true
Example 2:
Input: pattern = "abba", s = "dog cat cat fish"
Output: false
Example 3:
Input: pattern = "aaaa", s = "dog cat cat dog"
Output: false
Example 4:
Input: pattern = "abba", s = "dog dog dog dog"
Output: false
s guaranteed to be non-empty?
s will contain at least one word.s contain numbers, punctuation, etc.?
s will consist of lowercase alphabet characters only.pattern equal to the number of words in s?
s, their lengths in terms of elements (letters and words) should be equal.s into a list of words.s. If not, return false.def wordPattern(pattern: str, s: str) -> bool:
words = s.split()
if len(pattern) != len(words):
return False
char_to_word = {}
word_to_char = {}
for char, word in zip(pattern, words):
if char in char_to_word:
if char_to_word[char] != word:
return False
else:
char_to_word[char] = word
if word in word_to_char:
if word_to_char[word] != char:
return False
else:
word_to_char[word] = char
return True
s: O(n), where n is the length of the string s.k is the length of the pattern (or the number of words in s since they must be equal).Therefore, the overall time complexity is O(n + k), which simplifies to O(n) since the length of pattern k and the resulting word list length are bounded by the length of the input string s.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?