389. 找不同
给定两个字符串 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 只包含小写字母
题解:
直观上可以利用哈希表进行存储每个数组字母出现的次数,然后再对出现的次数进行一一的比对即可,即使用两个哈希表;也可以只用一个哈希表,让s数组进行“存储”,让t数组“删除”即可。
代码:
char findTheDifference(char * s, char * t){
int hash[26]={0};
for(int i=0;i<strlen(s);i++)
{
hash[s[i]-'a']++;
}
for(int i=0;i<strlen(t);i++)
{
hash[t[i]-'a']--;
}
char temp;
for(int i=0;i<26;i++)
{
if(hash[i]==-1)
{
temp = i+'a';
return temp;
}
}
return 1;
}
后来发现可以优化一下,不用“存储”,“删除”之后再进行比对,可以删除的过程中就进行一下比对过程,一旦发现不同立刻跳出即可。并且这样还省去了一个中间变量temp.
代码:
char findTheDifference(char * s, char * t){
int hash[26]={0};
for(int i=0;i<strlen(s);i++)
{
hash[s[i]-'a']++;
}
for(int i=0;i<strlen(t);i++)
{
hash[t[i]-'a']--;
if(hash[t[i]-'a']==-1)
{
return t[i];
}
}
return 1;
}