2
头图

find difference

Title description: Given two strings s and t , they only contain lowercase letters.

The string t is randomly rearranged from the string s , and then a letter is added at a random position.

Please find the letters added t

Please refer to LeetCode official website for example description.

Source: LeetCode
Link: https://leetcode-cn.com/problems/find-the-difference/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Solution 1: Binary operation

XOR operation: If the two values of a and b are not the same, the XOR result is 1. If the two values of a and b are the same, the XOR result is 0. So if a and b are two identical numbers, the result of the XOR must be 0.

The specific process is as follows:

  • If s is null or an empty string, it will directly return the first character of t
  • Otherwise, initialize a X is 0, traversing S and T each character in turn and X for XOR operation, since a and b only one character is not the same, so the final XOR is the letter added.
public class LeetCode_380 {
    public static char findTheDifference(String s, String t) {
        if (s == null || s.length() == 0) {
            return t.charAt(0);
        }
        int x = 0;
        for (int i = 0; i < s.length(); i++) {
            x ^= s.charAt(i);
            x ^= t.charAt(i);
        }
        x ^= t.charAt(t.length() - 1);
        return (char) x;
    }

    public static void main(String[] args) {
        System.out.println(findTheDifference("abcd", "abcde"));
    }
}
[Daily Message] Today’s results are yesterday’s sweat, and tomorrow’s success requires today’s efforts.

醉舞经阁
1.8k 声望7.1k 粉丝

玉树临风,仙姿佚貌!