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.根据每个字符char类型对应的int值进行累加,然后相减,得到差值。
public char findTheDifference(String s, String t) {
int charCodeS=0,charCodeT=0;
for(int i=0;i<s.length();i++){
charCodeS +=s.charAt(i);
}
for(int i=0;i<t.length();i++){
charCodeT +=t.charAt(i);
}
return (char)(charCodeT-charCodeS);
}
然后可以优化为一个for循环,直接在一个变量charCode上面加减。
public char findTheDifference(String s, String t) {
int charCode=t.charAt(s.length());
for (int i = 0; i < s.length(); i++) {
charCode -= (int)s.charAt(i);
charCode += (int)t.charAt(i);
}
return (char)charCode;
}
取得多出那一位的char字符的int值然后按照s(少的那一个字符串)进行循环,减去s的每一个char字符值,加上每一个t的char字符值。最后得到结果转换回char,即可以得到结果。
还有一个桶排序,没想明白。