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

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

内容简介:用字典来建立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
                
复制代码

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

查看所有标签

猜你喜欢:

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

Flexible Rails

Flexible Rails

Peter Armstrong / Manning Publications / 2008-01-23 / USD 44.99

Rails is a fantastic tool for web application development, but its Ajax-driven interfaces stop short of the richness you gain with a tool like Adobe Flex. Simply put, Flex is the most productive way t......一起来看看 《Flexible Rails》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具