題目描述
給定兩個字符串 s 和 t,它們只包含小寫字母。
字符串 t 由字符串 s 隨機重排,然后在隨機位置添加一個字母房蝉。
請找出在 t 中被添加的字母。
示例 1:
輸入:s = "abcd", t = "abcde"
輸出:"e"
解釋:'e' 是那個被添加的字母微渠。
示例 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 只包含小寫字母
解題思路
- 計數(shù)
使用數(shù)組記錄字符串s每個字母的出現(xiàn)次數(shù)搭幻,遍歷字符串t,對應字母次數(shù)減1逞盆,找到小于零的字母檀蹋,即為添加的字母。 - 求和
除了添加的字母纳击,字符串s和字符串t組成相同续扔,各自求和后的差即為添加的字母的ascii碼。 - 位運算
字符串s和字符串t中除了添加的字母出現(xiàn)奇數(shù)次焕数,其他所有的字母均出現(xiàn)偶數(shù)次,進行異或位運算刨啸,最后結果即為添加的字母堡赔。
源碼
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;
*/
// 官方-位運算
int ans=0;
for(char c:s)
{
ans^=c;
}
for(char c:t)
{
ans^=c;
}
return ans;
}
};
題目來源
來源:力扣(LeetCode)