290. Word Pattern
# Easy
class Solution:
def wordPattern(self, pattern: str, s: str) -> bool:
words = s.split(" ")
# edge case
if len(words) != len(pattern):
return False
# regular case
m1 = {}
m2 = {}
for x, y in zip(pattern, words):
if x in m1 and y in m2:
if m1[x] != y or m2[y] != x:
return False
else:
if x not in m1 and y not in m2:
m1[x] = y
m2[y] = x
else:
return False
return True
Last updated
Was this helpful?