Given two strings s and t which consist of only lowercase letters.
String t is generated by random shuffling stringsand 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.
Note
看成整体,加加减减,用异或或者一个变量都行
Code
public char findTheDifference(String s, String t) {
// Convert to arrays for easy access
char[] sChars = s.toCharArray();
char[] tChars = t.toCharArray();
// Initially, char code is the last t character, since that won't be included in the loop
int charCode = tChars[tChars.length - 1];
// For all positions (except the "bonus" one handled above), change running char total
for (int i = 0; i < s.length(); i++) {
charCode -= (int)sChars[i];
charCode += (int)tChars[i];
}
// Leftover amount is the value of bonus letter
return (char)charCode;
}
class Solution {
public char findTheDifference(String s, String t) {
char res = t.charAt(t.length() - 1);
for (int i = 0; i < s.length(); i++) {
res ^= t.charAt(i);
res ^= s.charAt(i);
}
return res;
}
}