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.
字符串t比s多一个字母,其余字母都一样,这里简单的用multiset完成,更好的方法是用位运算来实现(与136题有点像)。
代码1:
class Solution {
public:
char findTheDifference(string s, string t) {
multiset<char>ms;
for(int i=0;i<t.size();++i)
{
ms.insert(t[i]);
}
for(int i=0;i<s.size();++i)
{
ms.erase(ms.find(s[i]));
}
return *ms.begin();
}
};
代码2:
class Solution {
public:
char findTheDifference(string s, string t) {
int ret=0;
for(int i=0;i<s.size();i++)
{
ret^=s[i];
}
for(int i=0;i<t.size();i++)
{
ret^=t[i];
}
return ret;
}
};