力扣(LeetCode)389

8次阅读

共计 804 个字符,预计需要花费 3 分钟才能阅读完成。

题目地址:https://leetcode-cn.com/probl… 题目描述:给定两个字符串 s 和 t,它们只包含小写字母。
字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。
请找出在 t 中被添加的字母。
示例:
输入:s = “abcd”t = “abcde”
输出:e
解释:’e’ 是那个被添加的字母。
解答:这一题可以用两种解法。解法一:利用 hash 表存储第一个字符串的字母的数量,然后遍历第二个字符串的时候先查找到字母,然后把数量减一,如果减完之后小于 0,说明这个字母就是多出来的字母这里的 hash 表可以用一个数组来代替,因为这里不需要解决 hash 冲突!!!
java ac 代码:
class Solution {
public char findTheDifference(String s, String t) {

int[] hash = new int[‘z’+1];
for(int i = 0;i < s.length();i++)
hash[s.charAt(i)]++;
for(int i = 0;i < t.length();i++)
if(–hash[t.charAt(i)] < 0)
return t.charAt(i);
return ‘ ‘;

}
}

解法二:把这题看作是一个数组里除了一个数出现了一次,其他都出现了偶数次,然后找出这个数,可以利用异或,因为偶数个自己异或自己为 0,而 0 异或一个数就等于那个数本身,比如说,有偶数个 a, 现在这偶数个 a 异或结果为 0,a^a^a^a…^a=0, 而 0^b=b。java ac 代码
class Solution {
public char findTheDifference(String s, String t) {

char ans = 0;
for(int i = 0;i < s.length();i++)
ans ^= s.charAt(i);
for(int i = 0;i < t.length();i++)
ans ^= t.charAt(i);
return ans;
}
}

正文完
 0