力扣https://leetcode.cn/problems/word-pattern/description/?envTypestudy-plan-v2envIdtop-interview-150给定一种规律 pattern 和一个字符串 s 判断 s 是否遵循相同的规律。这里的 遵循 指完全匹配例如 pattern 里的每个字母和字符串 s 中的每个非空单词之间存在着双向连接的对应规律。具体来说pattern 中的每个字母都 恰好 映射到 s 中的一个唯一单词。s 中的每个唯一单词都 恰好 映射到 pattern 中的一个字母。没有两个字母映射到同一个单词也没有两个单词映射到同一个字母。示例1:输入: pattern abba, s dog cat cat dog输出: true示例 2:输入:pattern abba, s dog cat cat fish输出: false示例 3:输入: pattern aaaa, s dog cat cat dog输出: false提示:方法一哈希表class Solution: def wordPattern(self, pattern: str, s: str) - bool: s_words s.split( ) pattern_n, s_n len(pattern), len(s_words) if pattern_n ! s_n: return False pattern_dict, s_dict {}, {} for w, word in zip(pattern, s_words): if w in pattern_dict and pattern_dict[w] ! word or word in s_dict and s_dict[word] ! w: return False pattern_dict[w] word s_dict[word] w return Truefunc wordPattern(pattern string, s string) bool { word2ch : map[string]byte{} ch2word : map[byte]string{} words : strings.Split(s, ) if len(pattern) ! len(words) { return false } for i, word : range words { ch : pattern[i] if word2ch[word] 0 word2ch[word] ! ch || ch2word[ch] ! ch2word[ch] ! word { return false } word2ch[word] ch ch2word[ch] word } return true }