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:
1)hash map的方法,很简单,代码如下:
//hash map
char findTheDifference(string s, string t) {
int i, m1[26] = {0}, m2[26] = {0};
for(i = 0; i < s.size(); ++i) m1[s[i]-'a']++;
for(i = 0; i < t.size(); ++i) m2[t[i]-'a']++;
for(i = 0; i < 26; ++i)
if(m1[i]!=m2[i]) break;
return i+'a';
}
2)位操作,具体来说是XOR,例如,s = "abc", t = "cabd".把s和t中所有元素异或,即res = a^b^c^c^a^b^d。由于异或具有如下性质
1、交换律 a^b = b^a
2、结合律(即(a^b)^c == a^(b^c))
3、对于任何数x,都有x^x=0,x^0=x
4、自反性 A XOR B XOR B = A xor 0 = A
由上面的性质可知:res = (a^a)^(b^b)^(c^c)^d = d;这就找到了那个插入的多余的元素.代码如下:
char findTheDifference(string s, string t) {
int i, res = 0;
for(i = 0; i < s.size(); ++i) res ^= s[i];
for(i = 0; i < t.size(); ++i) res ^= t[i];
return res;
}