Word Pattern解题报告

https://leetcode.com/problems/word-pattern/

题目描述见链接

这道题开始我觉得很简单,把string分割之后,然后把分割之后的字符串和位置进行map。但是后来发现如果有重复的就不好处理,后来发现可以用两个hashmap,将string分割之后的字符和pattern中的字符进行映射,然后如果不相等,则报错。这样比较好的一点是可以支持多种pattern比如abcdaaabcd

代码:

class Solution(object):
    def wordPattern(self, pattern, str):
        """
        :type pattern: str
        :type str: str
        :rtype: bool
        """
        sl=str.split()
        if len(sl)!=len(pattern):
            return False;
        p={}
        sd={}
        for ptn,s in zip(pattern,sl):
            if ptn not in p:
                p[ptn]=s
            if s not in sd:
                sd[s]=ptn
            if p[ptn]!=s or sd[s]!=ptn:
                return False
        return True
       
在网上还看到了一个非常简洁的python:

class Solution(object):
    def wordPattern(self, pattern, str):
        """
        :type pattern: str
        :type str: str
        :rtype: bool
        """
        s = pattern
        t = str.split()
        return map(s.find, s) == map(t.index, t)
        
map函数的官方描述是:

Apply function to every item of iterable and return a list of the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. If one iterable is shorter than another it is assumed to be extended withNoneitems. If function isNone, the identity function is assumed; if there are multiple arguments, map() returns a list consisting of tuples containing the corresponding items from all iterables (a kind of transpose operation). The iterable arguments may be a sequence or any iterable object; the result is always a list.
也就是对list中的每一个元素实施指定的方法,返回的结果作为一个数组。

这个方法真是太厉害了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值