标题:389找不同-简单
题目
给定两个字符串 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
只包含小写字母
代码Java
// 通过了 但是很慢 14ms
public char findTheDifference(String s, String t) {
if (s.length() == 0)
return t.charAt(0);
// 1 将s中的元素映射到map中,key是元素值,value是存在个数
// 2 将t映射到map中,
// 3 若不存在 直接返回这个元素, 若存在则value-1, 当减到0时,则说明不存在,返回此元素
HashMap map = new HashMap();
for (int i = 0; i < s.length(); i++) {
Object get = map.get(s.charAt(i));
if (get != null) {
int count = (int) get + 1;
map.put(s.charAt(i), count);
} else {
map.put(s.charAt(i), 1);
}
}
for (int i = 0; i < t.length(); i++) {
Object o = map.get(t.charAt(i));
if (o == null)
return t.charAt(i);
else {
int count = (int) o - 1;
if (count < 0)
return t.charAt(i);
map.put(t.charAt(i), count);
}
}
return 'F';
}
// 相对较快 3ms
public char findTheDifference1(String s, String t) {
char[] chars = s.toCharArray();
char[] chart = t.toCharArray();
Arrays.sort(chars);
Arrays.sort(chart);
for (int i = 0; i < s.length(); i++) {
if (chars[i] != chart[i])
return chart[i];
}
return chart[s.length()];
}
// 异或两组数据 2ms
public char findTheDifference2(String s, String t) {
int sum = 0;
for (int i = 0; i < s.length(); i++) {
sum ^= s.charAt(i);
sum ^= t.charAt(i);
}
sum ^= t.charAt(s.length());
return (char) sum;
}