python-leetcode-单词规律
290. 单词规律 - 力扣(LeetCode)
class Solution:
def wordPattern(self, pattern: str, s: str) -> bool:
words = s.split()
# 如果长度不一致,直接返回 False
if len(pattern) != len(words):
return False
char_to_word = {}
word_to_char = {}
for char, word in zip(pattern, words):
# 检查 pattern -> word 的映射
if char in char_to_word:
if char_to_word[char] != word:
return False
else:
char_to_word[char] = word
# 检查 word -> pattern 的映射
if word in word_to_char:
if word_to_char[word] != char:
return False
else:
word_to_char[word] = char
return True