Given a law and a pattern string str, str determines whether to follow the same rule.
Here follow the exact match means, for example, there is a corresponding pattern regularity in two-way connection between each letter string str and each non-empty word.
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
Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/word-pattern
Establish a hash table mapping
class Solution:
def wordPattern(self, pattern: str, str: str) -> bool:
word_list = str.split()
if len(set(pattern))!= len(set(word_list)): #避免"abba","dog dog dog dog"
return False
if len(pattern)!=len(word_list): #长度不等,模式不同
return False
str_map = {}
for i,val in enumerate(pattern):
if val not in str_map.keys():
str_map[val]=word_list[i] #建立字母与单词的映射
if str_map[val]==word_list[i]:
continue
else:
return False
return True
LeetCode the comments of two lines of code from @ Miao Xiaowei https://leetcode-cn.com/u/mou-xiao-wei/
The original map can also use this:
class Solution:
def wordPattern(self, pattern: str, str: str) -> bool:
res=str.split()
return list(map(pattern.index, pattern))==list(map(res.index,res))
# pattern.index('a')返回pattern字符串中字符‘a’首次出现的位置
Two two comparison pattern and the words are equal or unequal while at the same time:
class Solution:
def wordPattern(self, pattern: str, str: str) -> bool:
word_list = str.split()
if len(set(pattern))!= len(set(word_list)):
return False
if len(pattern)!=len(word_list):
return False
for i in range(len(pattern)-1):
if pattern[i]==pattern[i+1] and word_list[i]!=word_list[i+1]:
return False
elif pattern[i]!=pattern[i+1] and word_list[i]==word_list[i+1]:
return False
return True