【LeetCode】389. Find the Difference 找不同(Easy)(JAVA)

【LeetCode】389. Find the Difference 找不同(Easy)(JAVA)

题目地址: https://leetcode-cn.com/problems/find-the-difference/

题目描述:

You are given two strings s and t.

String t is generated by random shuffling string s and then add one more letter at a random position.

Return the letter that was added to t.

Example 1:

Input: s = "abcd", t = "abcde"
Output: "e"
Explanation: 'e' is the letter that was added.

Example 2:

Input: s = "", t = "y"
Output: "y"

Example 3:

Input: s = "a", t = "aa"
Output: "a"

Example 4:

Input: s = "ae", t = "aea"
Output: "a"

Constraints:

  • 0 <= s.length <= 1000
  • t.length == s.length + 1
  • s and t consist of lower-case English letters.

题目大意

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

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

扫描二维码关注公众号,回复: 12599984 查看本文章

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

解题方法

  1. 这一题和数组中其他元素出现两次,唯一一个元素出现一次的题目类似
  2. 可以借用异或的特性: aba = b, 相当于重复的元素被异或两次最后被消除了
  3. 所以只要把 s 和 t 的所有元素异或一遍就是结果了
class Solution {
    public char findTheDifference(String s, String t) {
        char res = 0;
        for (int i = 0; i < s.length(); i++) {
            res ^= s.charAt(i);
            res ^= t.charAt(i);
        }
        res ^= t.charAt(t.length() - 1);
        return res;
    }
}

执行耗时:2 ms,击败了76.78% 的Java用户
内存消耗:37 MB,击败了37.49% 的Java用户

欢迎关注我的公众号,LeetCode 每日一题更新

猜你喜欢

转载自blog.csdn.net/qq_16927853/article/details/111879981