【LeetCode】找不同

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

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

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

 

示例:

输入:
s = "abcd"
t = "abcde"

输出:
e

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

思路:

解法1:利用HashMap的特性,遍历字符串s,将字符作为key,出现次数作为value,存入HashMap,然后遍历字符串t,如果字符在HashMap的value为1,则删除该键值对,如果大于1,则将value值减一,最终HashMap中剩下的key即为结果。

代码:

class Solution {
    public static char findTheDifference(String s, String t) {

        HashMap hm = new HashMap();
        for (int i = 0;i<s.length();i++)
        {
            if (!hm.containsKey(s.charAt(i)))
                hm.put(s.charAt(i),1);
            else
                hm.put(s.charAt(i),(int)hm.get(s.charAt(i))+1);
        }

        for (int i=0;i<t.length();i++)
        {
            if (!hm.containsKey(t.charAt(i)))
                hm.put(t.charAt(i),1);
            else if ((int)hm.get(t.charAt(i))==1)
            {
                hm.remove(t.charAt(i));
            }
            else if ((int)hm.get(t.charAt(i))>1)
                hm.put(t.charAt(i),(int)hm.get(t.charAt(i))-1);
        }

        Set set = hm.keySet();
        Iterator it = set.iterator();
        return (char)it.next();

    }
}

解法2:利用异或运算的特性(异或同一个值两次结果不变),对两个字符串中每一个字符做异或运算,最终得到的字符即为结果。

代码:

class Solution {
    public static char findTheDifference(String s, String t) {

        char ch = t.charAt(0);

        for(int i =0;i<s.length();i++)
        {
            ch ^= s.charAt(i);
            ch ^= t.charAt(i+1);
        }
        return ch;
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值