Leetcode_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.

     
思路:
      (1)题意为给定字符串s和字符串t,其中字符串t是在字符串s的任意位置增加一个字符构成的字符串,要求对比两个字符串找出这个字符。

      (2)该题比较简单。下面简单介绍几种解题思路:
      a、一种方法可以将两字符串转换为两个字符数组并排序,然后设定两个指针分别对数组中相同位置的字符进行对比,如果发现不同,则从字符串s中当前比较的字符即为所求。
      b、另一种方法可以用map将字符串t中的所有字符和字符对应的个数存储,然后遍历字符串s,如果从字符串s中取出的字符存在于map中,则将map中该字符对应的数值减1;如果不存在;则当前遍历的字符即为所求。
      c、还有一种方法是通过位运算,由于字符串s和字符串t中仅有一个字符不一样,那么将这两个字串中的所有字符按位异或(^),那么最后剩下的字符即为所求。还有其它很多方法这里就不列举了。

      (3)算法代码实现如下所示。希望对你有所帮助。


//解法 1
public class Solution {
    public char findTheDifference(String s, String t) {
         if (s == null || t == null)
            return ' ';
        char[] c1 = s.toCharArray();
        char[] c2 = t.toCharArray();
        Arrays.sort(c1);
        Arrays.sort(c2);
        int len = c1.length > c2.length ? c2.length : c1.length;
        for (int i = 0; i < len; i++) {
            if (c1[i] == c2[i]) {
                continue;
            } else {
                if (c1.length > c2.length) {
                    return c1[i];
                } else {
                    return c2[i];
                }
            }
        }

        return c1.length > c2.length ? c1[c1.length - 1] : c2[c2.length - 1];
    }
}
//解法2
public class Solution {
    public char findTheDifference(String s, String t) {
        if (s == null || t == null || t.length()==0)
            return ' ';
        if(s.length()==0 && t.length()!=0)
            return t.charAt(0);
        char c = s.charAt(0);
       for(int i = 1; i<s.length();i++) {
           c^=s.charAt(i);
       }
        for(char n : t.toCharArray()){
            c^=n;
        }
        return c;
    }
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值