题解 | #牛群智能指导系统#

牛群智能指导系统

https://www.nowcoder.com/practice/94e01098fe8f4941ba90fb64ab2d7025

  • 题目考察的知识点 : 字符串,哈希
  • 题目解答方法的文字分析:
  1. 先将 pattern 中每个字符对应的单词保存在一个哈希表 mapping 中,然后遍历 plan 中的所有单词,检查每个单词是否与相同位置上的 pattern 中的字符匹配。
  2. 使用 zip 函数将 pattern 和 plan 中的对应元素进行打包,然后依次比较每个对应的元素。如果当前字符已经在哈希表中出现过,那么就检查其对应的单词是否与当前单词相同;否则,就将其加入哈希表中。如果当前单词与之前不同的字符对应,则说明 plan 不符合相同的指导规律。当遍历结束后,如果 plan 符合相同的指导规律,则返回 True;否则,返回 False。
  • 本题解析所用的编程语言: Python
  • 完整且正确的编程代码

#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param pattern string字符串
# @param plan string字符串
# @return bool布尔型
#
class Solution:
    def isValidPattern(self, pattern: str, plan: str) -> bool:
        words = plan.split()
        if len(pattern) != len(words):
            return False

        mapping = {}
        used_words = set()

        for p, w in zip(pattern, words):
            if p in mapping:
                if mapping[p] != w:
                    return False
            else:
                if w in used_words:
                    return False
                mapping[p] = w
                used_words.add(w)

        return True
牛客高频top202题解系列 文章被收录于专栏

记录刷牛客高频202题的解法思路

全部评论

相关推荐

点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务