题目来源:
题目描述:
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: e Explanation: '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一下:
学而时习之,不然还会在同一块石头上被绊倒两次