1. 程式人生 > 其它 >Leetcode: NO.389 找不同 異或

Leetcode: NO.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 只包含小寫字母

連結:https://leetcode-cn.com/problems/find-the-difference

解題記錄

  • 直接計數s,然後比對t中字元
/**
 * @author: ffzs
 * @Date: 2020/12/18 上午8:00
 */
public class Solution {

    public char findTheDifference
(String s, String t) { int[] counter = new int[26]; for (int i = 0; i < s.length(); i++) { counter[s.charAt(i)-'a']++; } for (int i = 0; i < t.length(); i++) { int at = t.charAt(i) - 'a'; if (counter[at] > 0) counter[at]--; else
return t.charAt(i); } return 'a'; } }

image-20201218081229315

  • 通過異或求,兩個序列中沒有配對的字元就是後新增的字元
/**
 * @author: ffzs
 * @Date: 2020/12/18 上午8:07
 */
public class Solution2 {
    public char findTheDifference(String s, String t) {
        char[] sc = s.toCharArray();
        char[] tc = t.toCharArray();
        char res = tc[tc.length-1];
        for (int i = 0; i < sc.length; i++) {
            res ^= sc[i];
            res ^= tc[i];
        }
        return res;
    }
}

image-20201218081508153