Day13-290. Word Pattern

今日题目:290. Word Pattern(Easy)

Given a pattern and a string s, find if s follows the same pattern.Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in s.

Example 1:
Input: pattern = "abba", s = "dog cat cat dog"
Output: true

Example 2:
Input: pattern = "abba", s = "dog cat cat fish"
Output: false

Example 3:
Input: pattern = "aaaa", s = "dog cat cat dog"
Output: false

解题技巧

dictionary 是个好东西:))

My solution

class Solution:
    def wordPattern(self, pattern: str, s: str) -> bool:
        n = len(pattern)
        s = s.split(" ")
        temp = {}
        if n != len(s):
            return False
        
        for i in range(n):
            if pattern[i] in temp:
                if temp[pattern[i]] != s[i]:
                    return False
                    break

            else:
                if s[i] in temp.values():
                    return False
                    break
                else:
                    temp[pattern[i]] = s[i]
        return True

Result

https://ithelp.ithome.com.tw/upload/images/20210928/201408435ILUdcatXy.png


<<:  day13: 模组化好的写法 -单一功能原则(1)

>>:  【Day13】漏洞分析Vulnerability Analysis(二)

反馈与「大便三明治」

这篇我是在讨论提供反馈 (giving feedback)。但对主管来说,如何接受反馈 (takin...

# Day 28 Page Migration (三)

文件 原文文件:Page migration 翻译: Non-LRU 分页迁移 ==========...

【Day30】函式常见的陷阱题

今天来讲解 this 相关的陷阱题 第一题 myName = '全域'; var person = ...

[ 卡卡DAY 6 ] - React Native style 必懂之 Flexbox 弹性盒子(上)

在手机装置中, Flexbox 弹性盒子是一个重点样式 倘若你不懂,就只能躺着被打 orz Rea...

[Day24] 网格交易机器人-结尾

今天的目标是帮GridBot增加下单的函数(实际上这实作有些限制,所以我先把下实单的部分注解掉了),...