Word Pattern
Description:
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
Given pattern = “abba”, str = “dog cat cat dog”, return true.
Given pattern = “abba”, str = “dog cat cat fish”, return false.
Given pattern = “aaaa”, str = “dog cat cat dog”, return false.
Given pattern = “abba”, str = “dog dog dog dog”, return false.
Code:
1.
class Solution:
"""
@param pattern: a string, denote pattern string
@param str: a string, denote matching string
@return: an boolean, denote whether the pattern string and the matching string match or not
"""
def wordPattern(self, pattern, str):
# write your code here
st = str.split(' ')
map1, map2 = {}, {}
if len(st)!=len(pattern):
return False
for i in range(len(st)):
if st[i] in map2 and pattern[i] not in map1:
return False
elif pattern[i] in map1 and map1[pattern[i]] != st[i]:
return False
map1[pattern[i]] = st[i]
map2[st[i]] = 1
return True
2.
class Solution:
"""
@param pattern: a string, denote pattern string
@param str: a string, denote matching string
@return: an boolean, denote whether the pattern string and the matching string match or not
"""
def wordPattern(self, pattern, str):
# write your code here
st = str.split(' ')
if len(st)!=len(pattern):
return False
return len(set(pattern)) == len(set(st)) == len(set(zip(st, pattern)))