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;
}
posted @ 2016-09-02 00:15  罗伯特小咩  阅读(327)  评论(0编辑  收藏  举报