Given a
pattern
and a strings
, find ifs
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 ins
.
class Solution:
def wordPattern(self, pattern, s):
word = s.split(' ')
if len(word) != len(pattern):
return False
d = {}
for i in range(len(word)):
# key 没出现过
if word[i] not in d:
# value 出现过
if pattern[i] in d.values():
return False
d[word[i]] = pattern[i]
# key 和 value 不匹配
elif d[word[i]] != pattern[i]:
return False
return True