[更文刷题] 389. 找不同

112 阅读1分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第13天,点击查看活动详情

一、题目描述:

389. 找不同

给定两个字符串 st ,它们只包含小写字母。

字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。

请找出在 t 中被添加的字母。

示例 1:

输入:s = "abcd", t = "abcde"
输出:"e"
解释:'e' 是那个被添加的字母。

示例 2:

输入:s = "", t = "y"
输出:"y"

提示:

  • 0 <= s.length <= 1000
  • t.length == s.length + 1
  • s 和 t 只包含小写字母

二、思路分析:

开一个存储字母出现次数的数组,数组下标代表从 a-z 的字母,数组内容代表此字母出现的次数。

先存储字符串t的字母,然后遍历字符串s,对于s中出现的字母,将其在对应数组中的计数减去 1 即可。

最后遍历整个数组,找到不为零的下表,然后输出对应字母。

看答案学了个异或

根据异或算法的结合律,两个相同的数进行异或结果为0~ 把两个字符串中每个字符转为数字,然后进行异或运算即可。 最后剩下的结果再转为字符即为答案

A ^ A = 0

A ^ 0 = A

三、AC 代码:

class Solution {
    public char findTheDifference(String s, String t) {
        int lenS = s.length();
        int lenT = t.length();
        int numsOfChar = 26;/**26个字母*/
        int[] hashS = new int[numsOfChar];
        int[] hashT = new int[numsOfChar];

        for(int i = 0; i < lenS; i++){
            char ch = s.charAt(i);
            hashS[ch - 'a']++;
        }
        
        for(int i = 0; i < lenT; i++){
            char ch = t.charAt(i);
            hashT[ch - 'a']++;
        }

        for(int i = 0; i < numsOfChar; i++){
            if(hashS[i] != hashT[i]){
                return (char)(i+'a');
            }
        }
        return 'a';
    }
}
class Solution{
	public char findTheDifference(String s,String t){
		int a[]=new int[26];
		for(char c:s.toCharArray()){
			a[c-'a']++;
		}
		for(char c:t.toCharArray()){
			if(a[c-'a']==0)
				return c;
			else a[c-'a']--;
		}
		return 0;
	}
}

范文参考:

【找不同】 - 找不同 - 力扣(LeetCode)

求和计算差距 - 找不同 - 力扣(LeetCode)

位运算-思路同No.268题 - 找不同 - 力扣(LeetCode)