[Leet Code] Word Pattern

Input: pattern = "abba", s = "dog cat cat dog"
Output: true
Input: pattern = "abba", s = "dog cat cat fish"
Output: false
Input: pattern = "aaaa", s = "dog cat cat dog"
Output: false
Input: pattern = "abba", s = "dog dog dog dog"
Output: false
  • 1 <= pattern.length <= 300
  • pattern contains only lower-case English letters.
  • 1 <= s.length <= 3000
  • s contains only lower-case English letters and spaces ' '.
  • s does not contain any leading or trailing spaces.
  • All the words in s are separated by a single space.
class Solution(object):
def wordPattern(self, pattern, s):
"""
:type pattern: str
:type s: str
:rtype: bool
"""
s_list = []
pattern_list = []
s_current = ""
pattern_current = ""
s_count = 0
pattern_count = 0

previous_answers_s = {}
previous_answers_pattern = {}

for i in s.split(" "):
if i not in previous_answers_s:
s_count += 1
previous_answers_s[i] = s_count
s_list.append(s_count)
s_current = i
else:
s_list.append(previous_answers_s[i])
for i in pattern:
if i not in previous_answers_pattern:

pattern_count += 1
previous_answers_pattern[i] = pattern_count
pattern_list.append(pattern_count)
pattern_current = i
else:
pattern_list.append(previous_answers_pattern[i])
if str(pattern_list) == str(s_list):
return True
else:
return False

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store