[220117] Word Pattern

本文介绍了如何实现一个字符串模式匹配的算法,通过Python代码展示了一个简单的解决方案。该算法检查输入字符串`s`是否遵循给定的模式`pattern`,确保每个模式字母与字符串中的非空单词存在一一对应关系。如果匹配成功,返回True,否则返回False。
摘要由CSDN通过智能技术生成

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.

class Solution:
    def wordPattern(self, pattern, s):

        word = s.split(' ')
        if len(word) != len(pattern):
            return False

        d = {}

        for i in range(len(word)):
            # key 没出现过
            if word[i] not in d:
                # value 出现过
                if pattern[i] in d.values():
                    return False
                d[word[i]] = pattern[i]
            # key 和 value 不匹配
            elif d[word[i]] != pattern[i]:
                return False
        return True

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值