【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 随机重排,然后在随机位置添加一个字母。

请找出在 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 每日一题更新

你可能感兴趣的:(LeetCode,每日一题,字符串,leetcode,java,算法,数据结构)