389. Find the Difference(python+cpp)

题目:

Given two strings s and t which consist of only lowercase letters.
String t is generated by random shuffling string s and then add one more letter at a random position.
Find the letter that was added in t.
Example:

Input: s = "abcd" t = "abcde"
Output: e
Explanation: 'e' is the letter that was added.

题目
解法1:
先排序,然后找到第一个不同的,如果找不到,则返回长的那一个的最后一个元素。(太慢)
python代码:

class Solution(object):
    def findTheDifference(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: str
        """
        s_sorted=sorted(s)
        t_sorted=sorted(t)
        for i in range(len(s_sorted)):
            if s_sorted[i]!=t_sorted[i]:
                return t_sorted[i]
        return t_sorted[-1]

解法2:
数两个字符串中各个字母出现的个数,返回个数不同的那个字母。(python中用Counter)
python代码:

from collections import Counter
class Solution(object):
    def findTheDifference(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: str
        """
        count_s=Counter(s)
        count_t=Counter(t)
        for key in count_t:
            if key not in count_s or count_t[key]!=count_s[key]:
                return key

解法3:
这题类似于Single Number I 所以可以用异或做(震惊了)。
速度快的都是用异或做的。
python代码:

class Solution(object):
    def findTheDifference(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: str
        """
        init=0
        for _s in s:
            init^=ord(_s)
        for _t in t:
            init^=ord(_t)
        return chr(init)     

c++代码:

class Solution {
public:
    char findTheDifference(string s, string t) {
        int init=0;
        for (auto _s:s)
            init^=_s;
        for (auto _t:t)
            init^=_t;
        return (char)init;  
    }
};

总结:
可以用字典计数的做法,或者用异或,这题居然可以用异或做,简直震惊,所以做题的时候要合理联想啊!
发现一件事:代码一样的情况下,python导入包居然多花了10ms!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值