DescriptionSubmissionsSolutions
Total Accepted: 60224
Total Submissions: 117313
Difficulty: Easy
Contributor: LeetCode
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.
以前有个字符串,再给一个新的字符串,看新加的是哪一个
解法1:
class Solution {
public:
char findTheDifference(string s, string t) {
bool hap[26] ={ true};
for (int i = 0; i < t.size(); i++)
{
hap[t[i] - 'A' - 32]=false;
}
for (int i = 0; i < s.size(); i++)
{
hap[s[i] - 'A'-32]=true;
}
for (int i = 0; i < 26; i++)
{
if (hap[i] == false)
{
return char(i + 'A' + 32) ;
}
}
}
};
//很稳健的超时了,下面是大神的
解法2:
class Solution {
public:
char findTheDifference(string s, string t) {
unordered_map<char, int>a;//当然建立哈希表啊,老哥,char是索引类型,int为元素类型
for (char b : s)//遍历短的字符串
{
a[b]++;
}
for (char b : t)
{
if( --a[b]<0)//多余的那个自然就多减了
{
cout << b;//
}
}
}
解法3:
//运用按位异或解决: a*a=0;并且符合交换律
class Solution {
public:
char findTheDifference(string s, string t) {
char res=0;
for(char a:s)
{
res^=a;
}
for(char b:t)
{
res^=b;
}
return res;
}
加减法.............
class Solution {
public:
char findTheDifference(string s, string t) {
char res = 0;
for (char c : s) res -= c;
for (char c : t) res += c;
return res;
}
};
解法4:
class Solution {
public:
char findTheDifference(string s, string t) {
return accumulate(begin(s), end(s += t), 0, bit_xor<int>());
}
};