290 word pattern
290. Word Pattern
题目: https://leetcode.com/problems/word-pattern/
难度 : Easy
4.pattern = "abba", str = "dog dog dog dog" should return false.
因为这个的限制,所以中间加了一个loop用来查询是否这个a对应的已经出现过了。
不过其实也可以用两个dictionary来处理,可以O(n^3) -> O(n^2)
class Solution(object):
def wordPattern(self, pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
strList = str.split(' ')
if len(pattern) != len(strList):
return False
lookup = {}
for i in range(len(strList)):
if pattern[i] not in lookup:
for key in lookup:
if lookup[key] == strList[i]:
return False
lookup[pattern[i]] = strList[i]
elif lookup[pattern[i]] != strList[i]:
return False
return True
另外看到一段非常简短代码,使用了map函数,有待学习