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.
本题很简单,就是寻找额外添加的元素,其实使用Map计数统计即可,
下面是C++的做法,
直接统计然后计数即可
代码如下:
#include <iostream>
#include <vector>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <queue>
#include <stack>
#include <string>
#include <climits>
#include <algorithm>
#include <sstream>
#include <functional>
#include <bitset>
#include <numeric>
#include <cmath>
#include <regex>
using namespace std;
class Solution
{
public:
char findTheDifference(string s, string t)
{
vector<int> count1(26, 0);
vector<int> count2(26, 0);
for (char c : s)
count1[c - 'a']++;
for (char c : t)
count2[c - 'a']++;
for (int i = 0; i < 26; i++)
{
if (count1[i] != count2[i])
return (char)(i + 'a');
}
return 0;
}
};