290. Word Pattern
# Easy
Two methods:
Because this problem requireds one to one map, we need two maps, {word: letter} and {letter:word}
One hash map, each word and letter maps to its index of its first appearing in the lists
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
class Solution:
def wordPattern(self, pattern: str, s: str) -> bool:
words = s.split(" ")
# edge case
if len(words) != len(pattern):
return False
# regular case
m = {}
for i in range(len(pattern)):
letter = pattern[i]
word = words[i]
letter_key = 'letter_{}'.format(letter)
word_key = "word_{}".format(word)
if letter_key not in m:
m[letter_key] = i
if word_key not in m:
m[word_key] = i
if m[letter_key] != m[word_key]:
return False
return True
Last updated
Was this helpful?