这一题和之前做过的题目一样,都是建立pattern和string之间的哈希表,最后需要去重一下,代码如下:
class Solution(object):
def wordPattern(self, pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
l = str.split()
if len(pattern) != len(l):
return False
dic = {}
for i in range(len(pattern)):
if pattern[i] not in dic:
dic[pattern[i]] = l[i]
else:
if dic[pattern[i]] != l[i]:
return False
if len(set(dic.values())) != len(dic):
return False
else:
return True
网友评论