首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >leetcode389.Find The Difference

leetcode389.Find The Difference

作者头像
眯眯眼的猫头鹰
发布2019-03-13 16:37:55
发布2019-03-13 16:37:55
3540
举报

题目要求

代码语言:javascript
复制
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。则该字符就是多余的字符。

代码语言:javascript
复制
    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码。

代码语言:javascript
复制
    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;
    }
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019-02-12,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目要求
  • 思路一:字符数组
  • 思路二:求和
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档