[leetCode]389. 找不同 简单

题目

https://leetcode-cn.com/problems/find-the-difference/

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

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

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

计数

遍历s中的字符进行计数,再遍历t中的字符将对应的字符数量–,如果t中一个字符的数量为0那么该字符为新增的字符。

class Solution {
    public char findTheDifference(String s, String t) {
        if (s.length() == 0 || s.charAt(0) == ' ') return t.charAt(0);
        int[] counter = new int[26];
        for (int i = 0; i < s.length(); i++) {
            counter[s.charAt(i) - 'a']++;
        }
        for (int i = 0; i < t.length(); i++) {
            if (counter[t.charAt(i) - 'a'] <= 0) {
                return t.charAt(i);
            }
            counter[t.charAt(i) - 'a']--;
        }
        return ' ';
    }
}

求和

将两个字符串中的字符分别求和,两个字符串ASCII码的差值就是新增的字符。

class Solution {
    public char findTheDifference(String s, String t) {
        int as = 0, at = 0;
        for (char c : s.toCharArray()) {
            as += c;
        }
        for (char c : t.toCharArray()) {
            at += c;
        }
        return (char)(at - as);
    }
}

位运算

将题目转化为“只出现奇数次的字符”

class Solution {
    public char findTheDifference(String s, String t) {
        int ret = 0;
        for (char c : s.toCharArray()) {
            ret ^= c;
        }
        for (char c : t.toCharArray()) {
            ret ^= c;
        }
        return (char)ret;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值