Description
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.
感觉例子给的不是特别好,其实s和t的字母顺序是不一样的。
比如
Input:
s = “abcd”
t = “abedc”
Output:
e
解法1
和 leetcode136 Single Number 一样的解法~~
public char findTheDifference(String s, String t) {
char ch = t.charAt(t.length() - 1);
for(int i=0; i<t.length()-1; i++) {
ch ^= s.charAt(i);
ch ^= t.charAt(i);
}
return ch;
}
解法2
用ASCII码解决。把t中每个字母ASCII码相加,减去s中每个字母ASCII码相加,最后得到的结果即是结果的ASCII码。
public char findTheDifference(String s, String t) {
int code = t.charAt(t.length() - 1);
for(int i=0; i<t.length()-1; i++) {
code -= s.charAt(i);
code += t.charAt(i);
}
return (char)code;
}