題目描述
給定兩個(gè)字符串 s 和 t,它們只包含小寫(xiě)字母。
字符串 t 由字符串 s 隨機(jī)重排,然后在隨機(jī)位置添加一個(gè)字母。
請(qǐng)找出在 t 中被添加的字母。
示例 1:
輸入:s = "abcd", t = "abcde"
輸出:"e"
解釋:'e' 是那個(gè)被添加的字母。
示例 2:
輸入:s = "", t = "y"
輸出:"y"
示例 3:
輸入:s = "a", t = "aa"
輸出:"a"
示例 4:
輸入:s = "ae", t = "aea"
輸出:"a"
提示:
0 <= s.length <= 1000
t.length == s.length + 1
s 和 t 只包含小寫(xiě)字母
解題思路
- 計(jì)數(shù)
使用數(shù)組記錄字符串s每個(gè)字母的出現(xiàn)次數(shù),遍歷字符串t,對(duì)應(yīng)字母次數(shù)減1,找到小于零的字母,即為添加的字母。 - 求和
除了添加的字母,字符串s和字符串t組成相同,各自求和后的差即為添加的字母的ascii碼。 - 位運(yùn)算
字符串s和字符串t中除了添加的字母出現(xiàn)奇數(shù)次,其他所有的字母均出現(xiàn)偶數(shù)次,進(jìn)行異或位運(yùn)算,最后結(jié)果即為添加的字母。
源碼
class Solution {
public:
char findTheDifference(string s, string t) {
/*
vector<int> cnt(26,0);
char ans;
for(char c:s)
{
cnt[c-'a']++;
}
for(char c:t)
{
cnt[c-'a']--;
if(cnt[c-'a']<0)
{
ans=c;
}
}
return ans;
*/
/*
// 官方-求和
int as=0,at=0;
for(char c:s)
{
as+=c;
}
for(char c:t)
{
at+=c;
}
return at-as;
*/
// 官方-位運(yùn)算
int ans=0;
for(char c:s)
{
ans^=c;
}
for(char c:t)
{
ans^=c;
}
return ans;
}
};
題目來(lái)源
來(lái)源:力扣(LeetCode)