每日一道算法题--leetcode 290--单词规则--python

栏目: Python · 发布时间: 6年前

内容简介:用字典来建立pattern与str之间的对应关系,当对应关系出现对应不上的问题时,就说明不匹配了。这种方式时间复杂度是O(n)。

【题目描述】

每日一道算法题--leetcode 290--单词规则--python
【思路分析】

用字典来建立pattern与str之间的对应关系,当对应关系出现对应不上的问题时,就说明不匹配了。这种方式时间复杂度是O(n)。

【源代码】

class Solution:
    def wordPattern(self, pattern: str, str: str) -> bool:
        if len(pattern)-1!=str.count(' '):
            return False
        str_list=str.split(' ')
        dic={}
        for i,val in enumerate(pattern):
            if(val not in dic.keys()):
                if(str_list[i] in dic.values()):
                    return False
                else:
                    dic[val]=str_list[i]
            else:
                if(dic[val]!=str_list[i]):
                    return False    
        return True
                
复制代码

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Seasoned Schemer

The Seasoned Schemer

Daniel P. Friedman、Matthias Felleisen / The MIT Press / 1995-12-21 / USD 38.00

drawings by Duane Bibbyforeword and afterword by Guy L. Steele Jr.The notion that "thinking about computing is one of the most exciting things the human mind can do" sets both The Little Schemer (form......一起来看看 《The Seasoned Schemer》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

SHA 加密
SHA 加密

SHA 加密工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具