一起刷题吧
一、题意分析
输入:两个字符串
输出:如果第二个字符串与第一个字符串模式相同,则返回 true,否则返回 false
难度:简单
标签:哈希
示例1:
输入: pattern = “abba”, str = "dog cat cat dog"
输出: true
示例 2:
输入:pattern = “abba”, str = "dog cat cat fish"
输出: false
示例 3:
输入: pattern = “aaaa”, str = "dog cat cat dog"
输出: false
示例 4:
输入: pattern = “abba”, str = "dog dog dog dog"
输出: false
二、参考代码
这个题目就很简单啦,直接使用哈希表存储两者的对应关系就可以了,需要注意的是,需要使用两个哈希来存储对应关系,用一个哈希表会有问题,比如反例:
print(s.wordPattern("abba", "dog cat cat fish"))
print(s.wordPattern("abba", "dog dog dog dog"))
我的实现代码:
class Solution:
def wordPattern(self, pattern: str, s: str) -> bool:
if not pattern:
return not s
if not s:
return not pattern
i = 0
s = s.split(" ")
if len(s) != len(pattern):
return False
mapping = {}
rev = set()
while i < len(pattern):
if pattern[i] not in mapping:
if s[i] not in rev:
mapping[pattern[i]] = s[i]
rev.add(s[i])
else:
return False
else:
if mapping[pattern[i]] != s[i]:
return False
i += 1
return True
参考了下官方给的 python 代码示例,代码写得更加优雅,代码如下:
class Solution:
def wordPattern(self, pattern: str, s: str) -> bool:
word2ch = dict()
ch2word = dict()
words = s.split()
if len(pattern) != len(words):
return False
for ch, word in zip(pattern, words):
# 更简洁
if (word in word2ch and word2ch[word] != ch) or (ch in ch2word and ch2word[ch] != word):
return False
word2ch[word] = ch
ch2word[ch] = word
return True
# 作者:LeetCode-Solution
# 链接:https://leetcode-cn.com/problems/word-pattern/solution/dan-ci-gui-lu-by-leetcode-solution-6vqv/
# 来源:力扣(LeetCode)
# 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。