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.My solution:
public class Solution {
public char findTheDifference(String s, String t) {
int[] sum_s=new int[26];
int[] sum_t=new int[26];
int num_s=s.length();
int num_t=t.length();
char c;
int i;
for(i=0;i<num_s;++i){
int index=s.charAt(i)-97;
sum_s[index]++;
}
for(i=0;i<num_t;++i){
int index=t.charAt(i)-97;
sum_t[index]++;
}
for(i=0;i<26;++i){
if(sum_s[i]!=sum_t[i]){
i=i+97;
break;
}
}
c=(char) i;
return c;
}
}
a better solution with bit manipulation:
a xor a=0;
a xor 0=a;
a xor b=b xor a;
(a xor b) xor c=a xor (b xor c);
public class Solution {
public char findTheDifference(String s, String t) {
int len_s=s.length();
int len_t=t.length();
char c=t.charAt(len_t-1);
for(int i=0;i<len_t-1;++i){
c^=s.charAt(i);
c^=t.charAt(i);
}
return c;
}
}