Problem : https://leetcode.com/problems/word-pattern/
Use 2 hash maps to save the mapping relationship.
class Solution:
def wordPattern(self, pattern: str, str: str) -> bool:
word = str.split(' ')
w2p = defaultdict(lambda : '')
p2w = defaultdict(lambda : '')
if len(word) != len(pattern):
return False
for i in range(len(pattern)):
if pattern[i] not in p2w and word[i] not in w2p:
p2w[pattern[i]] = word[i]
w2p[word[i]] = pattern[i]
elif p2w[pattern[i]] != word[i] or w2p[word[i]] != pattern[i]:
return False
return True
No comments:
Post a Comment