Find the Difference

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.

我的思路: 利用哈希(桶排序?),开两个大小为26的int数组,利用下标表示二十六个字母,比较两者内容是否相同。

结果:可以通过,还需发现其他的可能性。

别的思路:

1. 位运算 by yuming.wei

class Solution {
public:
    char findTheDifference(string s, string t) {
        int ans = 0;
        for(int i = 0 ; i < s.length(); ++i) ans ^= s[i]^t[i];
        ans ^= t[t.length() - 1];
        return char(ans);
    }
};

不用解释了,非常简单直接的方法。其实和之前做过的一道题很像,但是没想起来。

2.C++特性 by Ren.W

class Solution {
public:
    char findTheDifference(string s, string t) {
        char diff = 0;
        int cnt[256] = {0};
        for (char c : s) cnt[c]++;
        for (char c : t) if (--cnt[c] < 0) return c;
        return diff;
    }
};

C++的一个新标准,有时间可以去学习一下。

3. 神似位运算的朴素巧解

char findTheDifference(char* s, char* t) {
    int sum1=0,sum2=0;
    for(;*s;s++)
        sum1+=*s;
    for(;*t;t++)
        sum2+=*t;
    return sum2-sum1;
}

转载于:https://www.cnblogs.com/sofiaT/p/5831907.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值