# 389. 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.

Example:

Input:
s = "abcd"
t = "abcde"

Output:
e

Explanation:
'e' is the letter that was added.


/*solution1,use a vector to compute the frequency,4ms*/
class Solution {
public:
char findTheDifference(string s, string t) {
vector<int> word(26,0);
for(int i=0;i<s.size();i++)
word[s[i]-'a']++;
for(int i=0;i<t.size();i++){
int tmp=word[t[i]-'a']--;
if(tmp==0)
return t[i];
}
return 'a';
}
};



/*solution2,use bit manipulation，4ms*/
class Solution {
public:
char findTheDifference(string s, string t) {
char tmp=0;
for(char a:s)
tmp^=a;
for(char b:t)
tmp^=b;
return tmp;
}
};


Stefan大神提出了一行代码解决问题的方案，运用了accumulate方法，思路上和第二种方法相同,代码如下:

/*solution 3,one-line version of solution2*/
class Solution {
public:
char findTheDifference(string s, string t) {
return accumulate(begin(s), end(s += t), 0, bit_xor<int>());
}
};


### 学籍管理系统文档

#### 北邮教务系统评教脚本

Published on September 17, 2017

#### 72.Edit distance

Published on September 17, 2017