參考鏈接:https://blog.csdn.net/coder_orz/article/details/51693647
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
.
Example 1:
Input: pattern = "abba"
, str = "dog cat cat dog"
Output: true
Example 2:
Input:pattern = "abba"
, str = "dog cat cat fish"
Output: false
Example 3:
Input: pattern = "aaaa"
, str = "dog cat cat dog"
Output: false
Example 4:
Input: pattern = "abba"
, str = "dog dog dog dog"
Output: false
方法一:就是建立兩個字典,進行雙向映射檢查。
class Solution(object):
def wordPattern(self, pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
str_list = str.strip().split()
if len(str_list) != len(pattern):
return "false"
dictmap = {}
mapval = {}
for i in range(len(pattern.strip())):
if pattern[i] in dictmap.keys():
if str_list[i] != dictmap[pattern[i]]:
return "false"
else:
#這個地方是爲了雙向映射的原因
if str_list[i] in mapval:
return "false"
dictmap[pattern[i]] = str_list[i]
mapval[str_list[i]] = pattern[i]
return "true"
方法二:記錄每個字符和單詞出現的第一個位置,使得每個字符和單詞兩邊出現的第一次位置都相同時,就能保證雙射。
class Solution(object):
def wordPattern(self, pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
words = str.split(' ')
if len(words) != len(pattern):
return False
if map(pattern.find, pattern) == map(words.index, words):
return "true"
else:
return "false"
方法三:('a',‘dog’)類似這種建立映射體系,這個長度和pattern及str中去重後的長度是相等的。
class Solution(object):
def wordPattern(self, pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
words = str.split(' ')
if len(words) != len(pattern):
return False
return len(set(pattern)) == len(set(words)) == len(set(zip(pattern, words)))