给定两个字符串 s 和 t,它们只包含小写字母。
字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。
请找出在 t 中被添加的字母。
示例:
输入: s = "abcd" t = "abcde" 输出: e 解释: 'e' 是那个被添加的字母。
思路:
解法1:利用HashMap的特性,遍历字符串s,将字符作为key,出现次数作为value,存入HashMap,然后遍历字符串t,如果字符在HashMap的value为1,则删除该键值对,如果大于1,则将value值减一,最终HashMap中剩下的key即为结果。
代码:
class Solution {
public static char findTheDifference(String s, String t) {
HashMap hm = new HashMap();
for (int i = 0;i<s.length();i++)
{
if (!hm.containsKey(s.charAt(i)))
hm.put(s.charAt(i),1);
else
hm.put(s.charAt(i),(int)hm.get(s.charAt(i))+1);
}
for (int i=0;i<t.length();i++)
{
if (!hm.containsKey(t.charAt(i)))
hm.put(t.charAt(i),1);
else if ((int)hm.get(t.charAt(i))==1)
{
hm.remove(t.charAt(i));
}
else if ((int)hm.get(t.charAt(i))>1)
hm.put(t.charAt(i),(int)hm.get(t.charAt(i))-1);
}
Set set = hm.keySet();
Iterator it = set.iterator();
return (char)it.next();
}
}
解法2:利用异或运算的特性(异或同一个值两次结果不变),对两个字符串中每一个字符做异或运算,最终得到的字符即为结果。
代码:
class Solution {
public static char findTheDifference(String s, String t) {
char ch = t.charAt(0);
for(int i =0;i<s.length();i++)
{
ch ^= s.charAt(i);
ch ^= t.charAt(i+1);
}
return ch;
}
}