You are given two strings s and t.
String t is generated by random shuffling string s and then add one more letter at a random position.
Return the letter that was added to t.
Example 1:
Input: s = “abcd”, t = “abcde”
Output: “e”
Explanation: ‘e’ is the letter that was added.
Example 2:
Input: s = “”, t = “y”
Output: “y”
Constraints:
0 <= s.length <= 1000
t.length == s.length + 1
s and t consist of lowercase English letters.
给出字符串s和字符串t,t比s多一个字母,找出这个字母。
思路:
利用ASCII码,把s中所有字母的ASCII码求和,t中所有ASCII码求和,它们的差值就是多出来的字母。
public char findTheDifference(String s, String t) {
if(s.length() == 0) return t.charAt(0);
int diff = 0;
int n = s.length();
for(int i = 0; i < n; i++) {
diff += t.charAt(i) - s.charAt(i);
}
diff += t.charAt(n);
return (char)diff;
}