Description
Given two strings s and t which consist of only lowercase letters. String t is generated by randomly 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.
Thinking Process
- The trick is to use XOR operation, since XOR of the same character will cancel out to 0.
- By scanning through both strings and XOR every letter, letters that appear in pairs will eventually cancel out, leaving the added letter behind
public char findTheDifference(String s, String t) {
char extraLetter = 0;
for(int i=0; i<t.length(); i++){
char c1 = (i < s.length()) ? s.charAt(i) : 0;
char c2 = t.charAt(i);
extraLetter ^= (c1 ^ c2);
}
return extraLetter;
}