【leetcode刷题】[简单]389. 找不同(find the difference)-java

117 篇文章 0 订阅

找不同 find the difference

题目

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

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

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

示例:

输入:
s = "abcd"
t = "abcde"

输出:
e

解释:
'e' 是那个被添加的字母。

代码模板:

class Solution {
    public char findTheDifference(String s, String t) {
        
    }
}

分析

两种解法:

  1. 分别算出ASCII码sum,再相减,得到的就是多余的那个char
  2. 异或,因为a^a=0,一直异或下去,最后就能得到多余的那个char

解答

方法一:sum之差

class Solution {
    public char findTheDifference(String s, String t) {
        int sumS = 0;
        int sumT = 0;
        for(int i =0;i < s.length();i++){
            sumS += s.charAt(i);
        }
        for(int j = 0;j<t.length();j++){
            sumT += t.charAt(j);
        }
        int result = sumT-sumS;
        return (char)result;
    }
}

方法二:异或

class Solution {
    public char findTheDifference(String s, String t) {
        int result=0;
        for(int i =0;i < s.length();i++){
            result ^= s.charAt(i);
        }
        for(int j = 0;j<t.length();j++){
            result ^= t.charAt(j);
        }
        return (char)result;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值