389. 找不同 (Python3)

Problem: 389. 找不同

思路

参考:

解题方法

  1. python的 coding 在确实有很多不同于Java,C++等方法的地方,得益于一些人们称为pythonic的特性,可以巧妙轻松的解决一些问题;
  2. python内置collections库的 Counter()非常适合此题,同时也要熟悉python中字典的减法;
  3. python中的 zip()方法非常适合将element-wise的元素进行打包,从而实现对成对元素的遍历。

Code

Code: python内置Counter()

class Solution:
    def findTheDifference(self, s: str, t: str) -> str:

        # python内置标准库collections中的Counter()方法
        # 返回str中每个char的计数,key-value pair的dictionary
        # python中的的dictionary可以实现减法
        # 把dictionary转化成list就可以索引
        return list(Counter(t) - Counter(s))[0]

Code: 排序后逐对比较

class Solution:
    def findTheDifference(self, s: str, t: str) -> str:
        # 排序,注意给s添加一个空字符,保证排序后和t长度相同
        s_, t_ = sorted(s) + list(' '), sorted(t)

        # 逐对比较,使用zip()打包函数
        for (char1, char2) in zip(s_, t_):
            if char1 != char2:
                return char2
  • 11
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值