题目:
Given a pattern
and a string str
, find if str
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 in str
.
Examples:
- pattern =
"abba"
, str ="dog cat cat dog"
should return true. - pattern =
"abba"
, str ="dog cat cat fish"
should return false. - pattern =
"aaaa"
, str ="dog cat cat dog"
should return false. - pattern =
"abba"
, str ="dog dog dog dog"
should return false.
Notes:
You may assume pattern
contains only lowercase letters, and str
contains lowercase letters separated by a single space.
最原始的想法是构建一个词典dict,将pattern中的每个字母与str中的每个单词相对应
1.pattern中的字母不存在于dict中,而且相对应的单词也不存在与dict的values中,dict[字母]=单词。否则,返回错误
2.若.pattern中的字母存在于dict中,且这个字母对应的单词同于dict中的对应,继续。否则,返回错误。
class Solution(object):
def wordPattern(self, pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
pattern_l,str_l = list(pattern),str.split()
dict = {}
if len(pattern_l)!=len(str_l):
return False
for index in range(len(pattern_l)):
if pattern_l[index] not in dict.keys():
if str_l[index] not in dict.values():
dict[pattern_l[index]]=str_l[index]
else:
return False
elif dict[pattern_l[index]]!=str_l[index]:
return False
return True