题解 | #牛群智能指导系统# 哈希表
牛群智能指导系统
https://www.nowcoder.com/practice/94e01098fe8f4941ba90fb64ab2d7025
知识点
哈希表
思路
把plan按照空格分割成字符串数组a.
如果两个字符串不一样长,则是不可以的。从左到右依次匹配s的字母和a的字符串,同时用哈希表记录s的字母和a的字符串的对应关系,以及a的被占用的字符串。在匹配过程中出现矛盾则返回 False。
时间复杂度
AC Code (Python)
from collections import defaultdict
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param pattern string字符串
# @param plan string字符串
# @return bool布尔型
#
class Solution:
def isValidPattern(self , s: str, plan: str) -> bool:
a = plan.split()
if len(a) != len(s): return False
d = defaultdict(str)
seen = set()
for i in range(len(a)):
if s[i] in d.keys():
if d[s[i]] != a[i]: return False
continue
if a[i] in seen: return False
seen.add(a[i])
d[s[i]] = a[i]
return True
查看12道真题和解析