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.
My original solution: using HashMap to store the count of appearance of letters in string s, and check if there is match in string t:
class Solution {
public char findTheDifference(String s, String t) {
Map<Character,Integer> map = new HashMap<>();
for(int i=0;i<s.length();i++){
int count=map.getOrDefault(s.charAt(i),0)+1;
map.put(s.charAt(i),count);
}
for(int i=0;i<t.length();i++){
if(!map.containsKey(t.charAt(i))) return t.charAt(i);
else{
int count = map.get(t.charAt(i));
if(count<1) return t.charAt(i);
map.put(t.charAt(i),--count);
}
}
return 0;
}
}
However, there is a much smarter way to use XOR.
Since 0^N=N, N^N=0,
So if string s and t is ever the same, the XOR of each letter in the 2 strings should be zero.
The leftover character should be the excessive one.
public char findTheDifference(String s, String t) {
char c = 0;
for (int i = 0; i < s.length(); ++i) {
c ^= s.charAt(i);
}
for (int i = 0; i < t.length(); ++i) {
c ^= t.charAt(i);
}
return c;
}