美文网首页
leetcode 389 找不同

leetcode 389 找不同

作者: 0error_ | 来源:发表于2019-10-15 20:21 被阅读0次

给定两个字符串 s 和 t,它们只包含小写字母。
字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。
请找出在 t 中被添加的字母。
示例:
输入:
s = "abcd"
t = "abcde"
输出:
e
解释:
'e' 是那个被添加的字母。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-the-difference
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

自己用HashMap写了一个

class Solution {
    public char findTheDifference(String s, String t) {
        Map<Character,Integer> sMap = new HashMap<>();
        Map<Character,Integer> tMap = new HashMap<>();
        for (char ss:s.toCharArray()){
            sMap.put(ss,sMap.getOrDefault(ss,0)+1);
        }
        for(char tt:t.toCharArray()){
            tMap.put(tt,tMap.getOrDefault(tt,0)+1);
        }
        for(char c: tMap.keySet()){
            if (sMap.getOrDefault(c,0)!= tMap.get(c)) return c;
        }
        throw null;
    }
}


看到有一个人的思路很好

image.png

用java实现了一下:

class Solution {
    public char findTheDifference(String s, String t) {
        int nums=0, numt=0;
        for (char ss:s.toCharArray()){
            nums+=ss;
        }
        for (char tt:t.toCharArray()){
            numt+=tt;
        }
        char c = (char)(numt-nums);
        return c;
    }
}


相关文章

  • LeetCode 389——找不同

    1. 题目 2. 解答 2.1. 方法一 将 s 和 t 转化为 Python 的列表,然后遍历列表 s 的元素...

  • leetcode 389 找不同

    给定两个字符串 s 和 t,它们只包含小写字母。字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。请...

  • 每日一题20201218(389. 找不同)

    389. 找不同[https://leetcode-cn.com/problems/find-the-differ...

  • Leetcode389. 找不同

    题目 给定两个字符串 s 和 t,它们只包含小写字母。 字符串 t 由字符串 s 随机重排,然后在随机位置添加一个...

  • LeetCode389.找不同

    给定两个字符串 s 和 t,它们只包含小写字母。 字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。...

  • LeetCode 389. 找不同

    1,位运算解决 这题说的是字符串t只比s多了一个字符,其他字符他们的数量都是一样的。如果我们把字符串s和t合并就会...

  • LeetCode 389. 找不同

    题目 给定两个字符串 s 和 t,它们只包含小写字母。 字符串 t 由字符串 s 随机重排,然后在随机位置添加一个...

  • 389. 找不同

    内容 给定两个字符串 s 和 t,它们只包含小写字母。 字符串 t 由字符串 s 随机重排,然后在随机位置添加一个...

  • 389-找不同

    找不同 题目 给定两个字符串 s 和 t,它们只包含小写字母。 字符串t由字符串s随机重排,然后在随机位置添加一个...

  • 389. 找不同

    【题目描述】给定两个字符串 s 和 t,它们只包含小写字母。字符串 t 由字符串 s 随机重排,然后在随机位置添加...

网友评论

      本文标题:leetcode 389 找不同

      本文链接:https://www.haomeiwen.com/subject/bbkemctx.html