1. 程式人生 > 其它 >【LeetCode】每日一題389. 找不同

【LeetCode】每日一題389. 找不同

技術標籤:每日一題leetcode演算法java

389. 找不同

給定兩個字串 s 和 t,它們只包含小寫字母。

字串 t 由字串 s 隨機重排,然後在隨機位置新增一個字母。

請找出在 t 中被新增的字母。

示例 1:

輸入:s = "abcd", t = "abcde"
輸出:"e"
解釋:'e' 是那個被新增的字母。

示例 2:

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

示例 3:

輸入:s = "a", t = "aa"
輸出:"a"

示例 4:

輸入:s = "ae", t = "aea"
輸出:"a"

提示:

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

方法一:

題比較簡單,求和再相減就是多的那個字元

public char findTheDifference(String s, String t) {
    int ans = 0;
    for (int i = 0; i < s.length(); i++) {
        ans -=
s.charAt(i); ans += t.charAt(i); } ans += t.charAt(t.length() - 1); return (char) ans; }

位運算

public char findTheDifference1(String s, String t) {
    int ans = 0;
    for (int i = 0; i < s.length(); i++) {
        ans ^= s.charAt(i);
        ans ^= t.charAt(i);
    }
    ans ^=
t.charAt(t.length() - 1); return (char) ans; }

執行結果

在這裡插入圖片描述