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

假设两个只包含小写字母的字符串s和t,其中t是s中字母的乱序,并在某个位置上添加了一个新的字母。问添加的这个新的字母是什么?

思路一:字符数组

我们可以利用一个整数数组来记录所有字符出现的次数,在s中出现一次相应计数加一,在t中出现一次则减一。最后只需要遍历整数数组检查是否有某个字符计数大于0。则该字符就是多余的字符。

    public char findTheDifference(String s, String t) {
        int[] count = new int[26];
        for(int i = 0 ; i<t.length() ; i++) {
            if(i != t.length()-1) {
                count[s.charAt(i)-'a']++;
            }
            count[t.charAt(i)-'a']--;
        }
        for(int i = 0 ; i<count.length ; i++) {
            if(count[i] != 0) {
                return (char)('a' + i);
            }
        }
        return 'a';
    }

思路二:求和

我们知道,字符对应的ascii码是唯一的,那么既然两个字符串相比只有一个多余的字符,那么二者的ascii码和相减就可以找到唯一的字符的ascii码。

    public char findTheDifference2(String s, String t){
        int value = 0;
        for(int i = 0 ; i<s.length() ; i++) {
            value -= s.charAt(i);
            value += t.charAt(i);
        }
        char result = (char)(value + t.charAt(t.length()-1)); 
        return result;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值