389. 找不同

给定两个字符串 s 和 t,它们只包含小写字母。

字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。

请找出在 t 中被添加的字母。

 

输入:s = "abcd", t = "abcde"
输出:"e"
解释:'e' 是那个被添加的字母。

思路:

其中T是由S元素随机重新排列的结果,其实就是找T比S多出来的那个字符是什么。

解法1:

意识流就会给每个元素计数。

class Solution {
public:
    char findTheDifference(string s, string t) 
    {
        unordered_map<char, int> ss;
        unordered_map<char, int> tt;
        for(auto a:s)
        {
            if (ss.find(a) == ss.end())
                ss.insert(make_pair(a,1));
            else
                ss[a] += 1;
        }

        for(auto b:t)
        {
            if(ss.find(b) == ss.end())
                return b;

            if (tt.find(b) == tt.end())
                tt.insert(make_pair(b,1));
            else
            {
                if(ss[b] == tt[b])
                    return b;
                tt[b] += 1;
            }
                
        }

        return 'a';
    }
};

方法二:求和

就很妙,多出来一个就可以减出来ASCII码

class Solution {
public:
    char findTheDifference(string s, string t) {
        int as = 0, at = 0;
        for (char ch: s) {
            as += ch;
        }
        for (char ch: t) {
            at += ch;
        }
        return at - as;
    }
};

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/find-the-difference/solution/zhao-bu-tong-by-leetcode-solution-mtqf/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

方法三:位运算

没太懂啥意思。

将两个字符串拼接成一个字符串,则问题转换成求字符串中出现奇数次的字符。

https://leetcode-cn.com/problems/single-number/类似?

class Solution {
public:
    char findTheDifference(string s, string t) {
        int ret = 0;
        for (char ch: s) {
            ret ^= ch;
        }
        for (char ch: t) {
            ret ^= ch;
        }
        return ret;
    }
};

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/find-the-difference/solution/zhao-bu-tong-by-leetcode-solution-mtqf/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值