
1、解题思路:哈希。两个字典。分别记录字母对应的单词和单词对应的字母,若不是对应的,则返回False。
知识点:字符串.split():将字符串按指定字符拆分成列表。没有参数则以空格拆分。
len(序列):获得序列(字符串、列表、集合等)的长度,即序列内有多少元素。
zip(序列1, 序列2):将两个序列按对应位置组成元组形式的可迭代对象。
元素 in 字典:判断元素是否在字典的键中。
字典[键]=值:给字典中的键修改值。或往字典中添加键值对。
注解:d1, d2 = {}, {} 即 d1={};d2={} 即变量d1、d2均为字典。
- class Solution:
- def wordPattern(self, pattern: str, s: str) -> bool:
- s1 = s.split()
- if len(pattern) != len(s1): return False
- d1, d2 = {}, {}
- for x,y in zip(pattern,s1):
- if (x in d1 and d1[x] != y) or (y in d2 and d2[y] != x):
- return False
- d1[x] = y
- d2[y] = x
- return True
2、解题思路:哈希。一个字典。记录字母对应的单词,若不是对应的,则返回False。
知识点:enumerate(序列):返回可迭代的序列下标和下标对应的元素。
元素 not in 字典:判断元素是否不在字典的键中。
字典.values():返回可迭代的字典的所有值。
序列[下标]:通过下标获取序列(字符串、列表、元组)中的元素。
注解:for循环中if下的continue:若满足条件,直接进入下一轮循环(若循环内continue后面还有代码,则跳过)。
- class Solution:
- def wordPattern(self, pattern: str, s: str) -> bool:
- s1 = s.split()
- if len(pattern) != len(s1): return False
- d = {}
- for i,x in enumerate(pattern):
- if x not in d and s1[i] not in d.values():
- d[x] = s1[i]
- elif x in d and s1[i] in d.values() and d[x] == s1[i]:
- continue
- else:
- return False
- return True
3、解题思路:若规律对应,则每个相同位置的字母和单词首次出现的位置应该相同,若不同,则不遵循相同的规律。
知识点:字符串.find(元素):查找元素,返回元素在字符串中第一次出现的位置。
序列.index(元素):返回元素在序列中(字符串、列表等)第一次出现的位置。
注:若没有找到元素,find返回-1,而index报错。
- class Solution:
- def wordPattern(self, pattern: str, s: str) -> bool:
- s1 = s.split()
- if len(pattern) != len(s1): return False
- for i,x in enumerate(pattern):
- if pattern.find(x) != s1.index(s1[i]):
- return False
- return True
4、解题思路:集合。字母、单词、字母和单词对应的元组形式的可迭代对象,三者去重后的长度应该相同,若不同则不遵循相同的规律。
知识点:set(...):转为集合,集合中的元素不重复。
- class Solution:
- def wordPattern(self, pattern: str, s: str) -> bool:
- s1 = s.split()
- return len(pattern) == len(s1) and len(set(pattern)) == len(set(s1)) == len(set(zip(pattern,s1)))