leetcode-389-find the difference

问题

题目:[leetcode-389]

思路

有一个问题是字符本生会重复。之前两次WA,就是考虑问题不全面。
两张哈希表,必有一个字符的哈希值会相差1。

代码

class Solution {
public:
    char findTheDifference(string s, string t) {
        int s_sz = s.size();
        int t_sz = t.size();

        int hash[128];
        memset(hash, 0, sizeof(hash));
        for( int i = 0; i < s_sz; ++i ){
            hash[s[i]] += 1;
        }

        int hash1[128];
        memset(hash1, 0, sizeof(hash1));
        for(int i = 0; i < t_sz; ++i){
            hash1[t[i]] += 1;
        }

        int ans = 0;
        for( int i = 0; i < 128; ++i )
        {
            if( hash[i] + 1 == hash1[i] )
            {
                ans = i;
                break;
            }
        }
        return (char)ans;
    }
};

思路1

当然,位运算也是可以做的。这不相当于给你一个数组,所有数出现两次,有一个出现三次。让你把出现三次的那个找出来。
疑惑操作即可。注意xor操作的两个特性:

  • a ^ 0 = a
  • a ^ a = 0(additive inverse)

代码1

class Solution {
public:
    char findTheDifference(string s, string t) {
        int s_sz = s.size();
        int t_sz = t.size();

        char res = 0;
        for( int i = 0; i < s_sz; ++i ){
            res ^= s[i];
        }
        for( int i = 0; i < t_sz; ++i ){
            res ^= t[i];
        }
        return res;
    }
};

思路2

当然,还有一种操作。其实和位运算的原理类似,先减去第一个第一个数组里面所有数,在加上第二个数组里面的所有数。这样,多余的那个数也出来了。

代码2

class Solution {
public:
    char findTheDifference(string s, string t) {
        int s_sz = s.size();
        int t_sz = t.size();

        int res = 0;
        for( int i = 0; i < s_sz; ++i ) res -= s[i];
        for(int i = 0; i < t_sz; ++i) res += t[i];

        return (char)res;
    }
};

思路3

还是思路1的办法,利用xor去做。只不过现在,用库的代码,写起来更简洁。
库的学习参考下面这两个链接:[accumulate][bit_xor<>]

代码3

class Solution {
public:
    char findTheDifference(string s, string t) {
        char res = 0;
        res = std::accumulate( s.begin(), s.end(), res,  bit_xor<int>() );
        res = std::accumulate( t.begin(), t.end(), res,  bit_xor<int>() );
        return (char)res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值