LeetCode 题解之 389. Find the Difference(使用位运算解决的问题)

389. Find the Difference

题目描述和难度

  • 题目描述:

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

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

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

示例:

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

输出:
e

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

思路分析

求解关键:受 LeetCode 第 136 题使用位运算找不同数字的启发,这道题可以如法炮制。

参考解答

参考解答1

public class Solution {

    // 只包含小写数字,干脆全部转成 0-25 的数字就好了
    // 根据题意,t 比 s 多 1 个字符,干脆初始值就取 t 的第 1 个字符
    public char findTheDifference(String s, String t) {
        int slen = s.length();
        int tlen = t.length();
        int res = t.charAt(0) - 'a';
        for (int i = 0; i < slen; i++) {
            res ^= (s.charAt(i) - 'a');
        }
        for (int i = 1; i < tlen; i++) {
            res ^= (t.charAt(i) - 'a');
        }
        return (char) (res + 'a');
    }
}

参考解答2

public class Solution2 {

    // 在编写注释的过程中发现,其实 char 就是整型数字,因此根本不用做转换
    public char findTheDifference(String s, String t) {
        int slen = s.length();
        int tlen = t.length();
        int res = t.charAt(0);
        for (int i = 0; i < slen; i++) {
            res ^= (s.charAt(i));
        }
        for (int i = 1; i < tlen; i++) {
            res ^= (t.charAt(i));
        }
        return (char) (res);
    }
}

本篇文章的地址为 https://liweiwei1419.github.io/leetcode-solution/leetcode-0389-find-the-difference ,如果我的题解有错误,或者您有更好的解法,欢迎您告诉我 liweiwei1419@gmail.com

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值