Q:
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.
问题:有两个字符串s和t,t是将s中所有字母打乱顺序并随意添加了一个字母构成的,请找出这个字母。
Example:
Input: s = "abcd" t = "abcde" Output: e Explanation: 'e' is the letter that was added.
代码:
public char findTheDifference(String s, String t) {
int cs[] = new int[26];
int ct[] = new int[26];
for(int i=0;i<s.length();i++){
cs[s.charAt(i)-'a']++;
}
for(int i=0;i<t.length();i++){
ct[t.charAt(i)-'a']++;
}
for(int i=0;i<26;i++){
if(cs[i]!=ct[i]) return (char)('a'+i);
}
return 'A';
}
思路二:将两个字符串转化为字符数组,然后分别按ASCII码将数组加起来,用t数组的和减去s数组的和即为所加字母的ASCII码。
代码:
public char findTheDifference(String s, String t) {
char[] array1 = s.toCharArray();
char[] array2 = t.toCharArray();
int asciis = 0;
int asciit = 0;
for(int i = 0; i < array1.length; i++){
asciis += (int)array1[i];
}
for(int i = 0; i < array2.length; i++){
asciit += (int)array2[i];
}
return (char)(asciit-asciis);
}