Problem
Given a pattern and a string s, find if s 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 s.文章来源:https://www.toymoban.com/news/detail-725447.html
Algorithm
Use the dictionary to save the two list.文章来源地址https://www.toymoban.com/news/detail-725447.html
Code
class Solution:
def wordPattern(self, pattern: str, s: str) -> bool:
plen = len(pattern)
dict_p = dict()
dict_s = dict()
word = ""
index = 0
for c in s:
if c >= 'a' and c <= 'z':
word += c
else:
if index >= plen:
return False
pi = pattern[index]
if index < plen and not pi in dict_p and not word in dict_s:
dict_p[pi] = word
dict_s[word] = pi
elif pi in dict_p and dict_p[pi] != word or word in dict_s and dict_s[word] != pi:
return False
index += 1
word = ""
if index >= plen:
return False
pi = pattern[index]
if index < plen and not pi in dict_p and not word in dict_s:
dict_p[pi] = word
dict_s[word] = pi
elif pi in dict_p and dict_p[pi] != word or word in dict_s and dict_s[word] != pi:
return False
for i in range(index, plen):
if not pattern[i] in dict_p:
return False
return True
到了这里,关于Leetcode 290. Word Pattern的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!