leetcode_389

1,题目大意

给定两个由小写字母构成的字符串s和t,t是由s中的所有字母随机打乱后在任一位置插入一个新字母构成的字符串。请在t中找出新加入的字母。

2,分析
(1)通过计数。用count[26]数组记录26个字母出现的次数,统计s时候做加法,统计t的时候做减法,最后为-1的就是解。(直接访问,很快)

(2)用map计数。和上面一样,只是把数组换成了map。

(3)用异或。把s,t按字符做异或,得到的就是答案。
异或的性质:
a ^ b = b ^ a
a ^ b ^ c = a ^ (b ^ c)
a ^ 0 = a
a ^ a = 0

3,java代码
(1)数组计数

public static char findTheDifference(String s, String t) {
        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] == -1) {
                return (char)(i + 'a');
            }
        }
        return 'z';
    }

(2)map计数

public static char findTheDifference2(String s, String t) {
        HashMap<Character, Integer> count = new HashMap<Character, Integer>();
        for(int i=0;i<s.length();i++) {
            if(count.get(s.charAt(i)) == null)
                count.put(s.charAt(i), 1);
            else {
                count.put(s.charAt(i), count.get(s.charAt(i))+1);
            }
        }
        for(int i=0;i<t.length();i++) {
            if(count.get(t.charAt(i)) == null) {
                return t.charAt(i);
            }else {
                count.put(t.charAt(i), count.get(t.charAt(i))-1);
            }
        }
        for(Character c:count.keySet()) {
            if(count.get(c) == -1) {
                return c;
            }
        }
        return 'z';
    }

(3)异或:很简单,看python代码

4,代码python
(1)数组计数:很快,在90%以上

class Solution(object):
    def findTheDifference(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: str
        """
        count = [0]*26
        for i in s:
            count[ord(i) - 97] +=1
        for i in t:
            count[ord(i) - 97] -=1
        return chr(count.index(-1) + 97)

(2)map计数:和java类似

(3)异或:本以为会比数组计数快,可能是异或运算本身耗时,比例67%左右

class Solution(object):
    def findTheDifference(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: str
        """
        a = 0
        for i in s:
            a = a ^ ord(i)
        for i in t:
            a = a ^ ord(i)
        return chr(a)

(4)改进异或:异或可能运算本身耗时,试一试用减法代替果然很快,比数组计数还快一点,可以达到95%以上

class Solution(object):
    def findTheDifference(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: str
        """
        res = ord(t[-1])
        for i in xrange(len(s)):
            res = res + ord(t[i]) - ord(s[i])
        return chr(res)
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值