LeetCode389_389. 找不同

LeetCode389_389. 找不同

一、描述

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

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

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

示例 1:

输入:s = "abcd", t = "abcde"
输出:"e"
解释:'e' 是那个被添加的字母。

示例 2:

输入:s = "", t = "y"
输出:"y"

提示:

0 <= s.length <= 1000
t.length == s.length + 1
s 和 t 只包含小写字母

二、题解

方法一:

1、将两个字符串转化为字符数组。
2、对两个字符数字排序。
3、对两个字符字符数组中的字符进行比对,返回t中多的那个即可。

    //AC Your runtime beats 30.72 % of java submissions.
    //54 / 54 test cases passed.	Status: Accepted	Runtime: 10 ms
    public char findTheDifference2(String s, String t) {
    
    
        char res = 0;//char类型初始化
        char[] chs = s.toCharArray();
        char[] cht = t.toCharArray();
        Arrays.sort(chs);
        Arrays.sort(cht);
        System.out.println(chs);
        System.out.println(cht);
        for (int i = 0; i < chs.length; i++) {
    
    
            if (chs[i] != cht[i]) {
    
    
                res = cht[i];
                break;
            }
        }
        if (res == 0) {
    
    
            res = cht[cht.length - 1];
        }
        return res;
    }

LeetCode 367. 有效的完全平方数
LeetCode 371. 两整数之和
LeetCode 383. 赎金信
LeetCode 387. 字符串中的第一个唯一字符
LeetCode 389. 找不同
LeetCode 404. 左叶子之和
LeetCode 412. Fizz Buzz
LeetCode 414. 第三大的数
LeetCode 415. 字符串相加
LeetCode 434. 字符串中的单词数



声明:
        题目版权为原作者所有。文章中代码及相关语句为自己根据相应理解编写,文章中出现的相关图片为自己实践中的截图和相关技术对应的图片,若有相关异议,请联系删除。感谢。转载请注明出处,感谢。


By luoyepiaoxue2014

B站: https://space.bilibili.com/1523287361 点击打开链接
微博: http://weibo.com/luoyepiaoxue2014 点击打开链接

猜你喜欢

转载自blog.csdn.net/luoyepiaoxue2014/article/details/129992761