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)))