//给定两个字符串 s 和 t,它们只包含小写字母。
//
// 字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。
//
// 请找出在 t 中被添加的字母。
//
//
//
// 示例 1:
//
// 输入:s = "abcd", t = "abcde"
//输出:"e"
//解释:'e' 是那个被添加的字母。
//
//
// 示例 2:
//
// 输入:s = "", t = "y"
//输出:"y"
//
//
// 示例 3:
//
// 输入:s = "a", t = "aa"
//输出:"a"
//
//
// 示例 4:
//
// 输入:s = "ae", t = "aea"
//输出:"a"
//
//
//
//
// 提示:
//
//
// 0 <= s.length <= 1000
// t.length == s.length + 1
// s 和 t 只包含小写字母
//
// Related Topics 位运算 哈希表
// 👍 249 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public char findTheDifference(String s, String t) {
int sizeS = s.length();
int sizeT = t.length();
if(sizeS == 0){
return t.charAt(0);
}
int [] table = new int[26];
for(int i = 0;i < sizeT;i++){
if(i< sizeS){
//获取i索引位置的字符-a,是为了获取asicc码,相当于-97
table[s.charAt(i)-'a']++;
}
// 这个获取同样索引位置的字母不一定是一样的,但是--,除非假设s和t字符前面的位置都一样
table[t.charAt(i)-'a']--;
}
for(int i =0; i<26;i++){
if(table[i]!=0){
return (char)('a'+i);
}
}
return 'a';
}
}
//leetcode submit region end(Prohibit modification and deletion)
这道题有几个特点,所以看起来是比较简单的。 1.s和t 是字符1vs 1位置对称的,所以能用+1,-1对偶来消解比较 2.当然如果不对称最终只要获取不为0的字符也是可以 3. 另外这首题做了一层转换,把字母减去‘a’来得到较小数字,方便存到0-25的数组里。