給定兩個字符串 s 和 t,它們只包含小寫字母。
字符串 t 由字符串 s 隨機重排,然後在隨機位置添加一個字母。
請找出在 t 中被添加的字母。
示例:
輸入: s = "abcd" t = "abcde" 輸出: e 解釋: 'e' 是那個被添加的字母。
方法1
class Solution {
public char findTheDifference(String s, String t) {
int[] a = new int[26];
int[] b= new int[26];
int lenA = s.length();
int lenB = t.length();
for(int i = 0;i < lenA;i++){
a[s.charAt(i) - 'a'] += 1;
b[t.charAt(i) - 'a'] += 1;
}
b[t.charAt(lenB - 1) - 'a'] += 1;
for(int i = 0;i < a.length;i++){
if(a[i] != b[i]){
return (char)('a' + i);
}
}
return 'a';
}
}
方法2
思路
與在一堆重複兩次的數中找出一個單獨只存在一個的數的問題一樣,用異或操作消除所有重複的元素,剩餘的元素即爲所求
public static char findTheDifference(String s, String t) {
char[] arr1 = s.toCharArray();
char[] arr2 = t.toCharArray();
int temp = 0;
for(char c:arr1){
temp ^= c;
}
for(char c:arr2){
temp ^= c;
}
return (char)temp;
}