原题链接在这里:https://leetcode.com/problems/find-the-difference/

题目:

Given two strings s and t which consist of only lowercase letters.

String t is generated by random shuffling string s and then add one more letter at a random position.

Find the letter that was added in t.

Example:

Input:
s = "abcd"
t = "abcde"

Output:
e

Explanation:
'e' is the letter that was added.

题解:

可用Bit Manipulation, t的每个char ^ s的每个char, 剩下的就是diff.

Time Complexity: O(t.length()). Space: O(1).

AC Java:

 1 public class Solution {
 2     public char findTheDifference(String s, String t) {
 3         char c = t.charAt(t.length()-1);
 4         for(int i = s.length()-1; i>=0; i--){
 5             c ^= s.charAt(i);
 6             c ^= t.charAt(i);
 7         }
 8         return c;
 9     }
10 }

也可以直接采用char code 得出diff

Time Complexity: O(t.length()). Space: O(1).

AV Java:

 1 public class Solution {
 2     public char findTheDifference(String s, String t) {
 3         int charCodeDiff = 0;
 4         for(int i = 0; i<s.length(); i++){
 5             charCodeDiff -= (int)s.charAt(i);
 6             charCodeDiff += (int)t.charAt(i);
 7         }
 8         charCodeDiff += t.charAt(t.length()-1);
 9         return (char)charCodeDiff;
10     }
11 }

类似Single Number.