java 位运算 求和_LeetCode389.找不同(Java位运算+求和+计数)

题目

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

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

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

示例 1:

输入:s = “abcd”, t = “abcde”

输出:“e”

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

方法一:位运算

我们知道

a^0=a; a ^a =0;

所以如果是多余的字符,则结果不会为0,因为是在s的基础上进行新增一个字符,所以除开新增的字符,在异或过程中,两两抵消,最后剩下的就是新增的字符了。

// 位运算

public char findTheDifference(String s, String t) {

int temp = 0;

for (int i = 0; i < s.length(); i++) {

temp ^= s.charAt(i);

}

for (int i = 0; i < t.length(); i++) {

temp ^= t.charAt(i);

}

//temp=0^a^b^c^d;

//又继续temp^a^b^c^d^e;

return (char) temp;

}

方法二:求和

public char findTheDifference(String s, String t) {

int s1 = 0;

int s2 = 0;

for (int i = 0; i < s.length(); i++) {

s1 += s.charAt(i);

}

for (int i = 0; i < t.length(); i++) {

s2 += t.charAt(i);

}

return (char) (s2 - s1);

}

方法三:计数

public char findTheDifference(String s, String t) {

if (s.length() == 0) {

return t.charAt(0);

}

int[] count = new int[26];

for (int i = 0; i < s.length(); i++) {

count[s.charAt(i) - 'a']++;

}

for (int i = 0; i < t.length(); i++) {

count[t.charAt(i) - 'a']--;

}

for (int i = 0; i < count.length; i++) {

if (count[i] != 0) {

return (char) (i + 'a');

}

}

return ' ';

}

end.

标签:Java,charAt,LeetCode389,int,++,char,计数,length,String

来源: https://blog.csdn.net/weixin_44998686/article/details/111356291

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值