題目要求
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,其中t是s中字母的亂序,並在某個位置上添加了一個新的字母。問添加的這個新的字母是什麼?
思路一:字符數組
我們可以利用一個整數數組來記錄所有字符出現的次數,在s中出現一次相應計數加一,在t中出現一次則減一。最後只需要遍歷整數數組檢查是否有某個字符計數大於0。則該字符就是多餘的字符。
public char findTheDifference(String s, String t) {
int[] count = new int[26];
for(int i = 0 ; i<t.length() ; i++) {
if(i != t.length()-1) {
count[s.charAt(i)-'a']++;
}
count[t.charAt(i)-'a']--;
}
for(int i = 0 ; i<count.length ; i++) {
if(count[i] != 0) {
return (char)('a' + i);
}
}
return 'a';
}
思路二:求和
我們知道,字符對應的ascii碼是唯一的,那麼既然兩個字符串相比只有一個多餘的字符,那麼二者的ascii碼和相減就可以找到唯一的字符的ascii碼。
public char findTheDifference2(String s, String t){
int value = 0;
for(int i = 0 ; i<s.length() ; i++) {
value -= s.charAt(i);
value += t.charAt(i);
}
char result = (char)(value + t.charAt(t.length()-1));
return result;
}