389. Find the Difference

本文介绍了一种通过比较两个字符串来找出其中一个字符串相对于另一个字符串新增加的字符的方法。使用了两种不同的解决方案:一种是通过统计字符出现次数的差异来找到新增的字符;另一种则是利用位操作符进行异或运算,巧妙地简化了问题,直接找到了新增的字符。

Given two strings s and t which consist of only lowercase letters.

String t is generated by random shuffling string s and then add one more letter at a random position.

Find the letter that was added in t.

Example:

Input:
s = "abcd"
t = "abcde"

Output:
e

Explanation:
'e' is the letter that was added.
My solution:
public class Solution {
    public char findTheDifference(String s, String t) {
        int[] sum_s=new int[26];
        int[] sum_t=new int[26];
        int num_s=s.length();
        int num_t=t.length();
        char c;
        int i;
        for(i=0;i<num_s;++i){
            int index=s.charAt(i)-97;
            sum_s[index]++;
            }
        for(i=0;i<num_t;++i){
            int index=t.charAt(i)-97;
            sum_t[index]++;
            }
        for(i=0;i<26;++i){
            if(sum_s[i]!=sum_t[i]){
                i=i+97;
                break;
            }
            }
        c=(char) i;    
        return c;    
        
    }
}

a better solution with bit manipulation:

a xor a=0;

a xor 0=a;

a xor b=b xor a;

(a xor b) xor c=a xor (b xor c);

public class Solution {
    public char findTheDifference(String s, String t) {
        int len_s=s.length();
        int len_t=t.length();
        char c=t.charAt(len_t-1);
        for(int i=0;i<len_t-1;++i){
            c^=s.charAt(i);
            c^=t.charAt(i);
            }
        return c;    
        
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值