LeetCode find the difference

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

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

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

示例:

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

输出:
e

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

[java]

1.
public static char findTheDifference(String s, String t) {
        char[] str_s = s.toCharArray();
        char[] str_t = t.toCharArray();
        Arrays.sort(str_s);
        Arrays.sort(str_t);
        int i = 0;
        for(i = 0; i < str_s.length; i++) {
        	if(str_t[i] != str_s[i])
        		return str_t[i];
        }
		return str_t[i];
    }

####2.空间复杂度和时间复杂度比起上面的都降低了

//空间复杂度和时间复杂度都降低了
	public char findTheDifference(String s, String t) {
        int a[]=new int[26];
        for(int i=0;i<s.length();i++)
            a[s.charAt(i)-'a']++;
        for(int j=0;j<t.length();j++)
            a[t.charAt(j)-'a']--;
        for(int k=0;k<a.length;k++){
            if(a[k]!=0)
                return (char)(k+'a');
        }
        return 0;
	}
3.利用位运算去解决
在一堆重复两次的数中找出一个单独只存在一个的数的问题一样,用异或操作消除所有重复的元素,剩余的元素即为所求
	public char findTheDifference(String s, String t) {
        
        char res = 0;
        for(int i = 0; i < s.length(); i++)
            res ^= s.charAt(i);
        for(int i = 0; i < t.length(); i++)
            res ^= t.charAt(i);
        return res;
	}
}

文末附上某不知名大佬的代码(膜拜.jpg):

public char findTheDifference(String s, String t) {
        return (char) (s + t).chars().reduce(0, (c, d) -> c ^ d);
    }

参考资料 :
https://www.jianshu.com/p/00f7cd6b1e86

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值