【LeetCode】389. Find the Difference 找不同(Easy)(JAVA)每日一題
阿新 • • 發佈:2020-12-19
技術標籤:LeetCode 每日一題字串leetcodejava演算法資料結構
【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 中被新增的字母。
解題方法
- 這一題和陣列中其他元素出現兩次,唯一一個元素出現一次的題目類似
- 可以借用異或的特性: aba = b, 相當於重複的元素被異或兩次最後被消除了
- 所以只要把 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使用者