通过异或快速找到不同的字符元素

来源:互联网 发布:黑客获取数据 编辑:程序博客网 时间:2024/06/05 00:53

题目来源:

点击打开链接


题目描述:

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:eExplanation:'e' is the letter that was added.

我的解决方案:

class Solution {public:    char findTheDifference(string s, string t) {        int table[26]={0};        for(int i=0;i<s.size();++i)        {            int index= s[i] -'a';            (table[index])++;        }        for(int i=0;i<t.size();++i)        {            int index=t[i]-'a';            table[index]--;            if(table[index]==-1)              return (char)('a'+index);        }    }};

思考:

此题其实和之前做过的single number很类似,用异或的方式其实可以很快的求解,但一时没想到,所以还是采用了笨办法完成的求解.异或计算的原理如下:

A^A=0(异或的归律)所以A^B^A=B,由题目可知要找到唯一多余的元素,只需要把全部元素依次求一遍异或计算,最后得到的结果,就是唯一多余的元素,代码如下:

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

另外对于异或计算,这位博主的博客写的挺不错的,mark一下:

点击打开链接

学而时习之,不然还会在同一块石头上被绊倒两次

0 0
原创粉丝点击