题目
代码部分一(14ms 36.69%)
class Solution {
public char findTheDifference(String s, String t) {
char res = ' ';
Map<Character, Integer> mapS = new HashMap<Character, Integer>();
Map<Character, Integer> mapT = new HashMap<Character, Integer>();
int len = s.length();
for(int i = 0; i < len; i++)
{
mapS.put(s.charAt(i),mapS.getOrDefault(s.charAt(i),0)+1);
}
len = t.length();
for(int i = 0; i < len; i++)
{
mapT.put(t.charAt(i),mapT.getOrDefault(t.charAt(i),0)+1);
}
for(Character ch : mapT.keySet())
{
if(!mapS.containsKey(ch))
{
res = ch.toString().charAt(0);
break;
}
else if(mapS.get(ch) != mapT.get(ch))
{
res = ch.toString().charAt(0);
break;
}
}
return res;
}
}
代码部分二(6ms 91.36%)
class Solution {
public char findTheDifference(String s, String t) {
int[] numsS = new int [1000];
int[] numsT = new int [1000];
Arrays.fill(numsS, 1000);
Arrays.fill(numsT, 1000);
int len = s.length();
for(int i = 0; i < len; i++)
{
numsS[(int)(s.charAt(i))]++;
}
len = t.length();
for(int j = 0; j < len; j++)
{
numsT[(int)(t.charAt(j))]++;
}
for(int i = 0; i < numsS.length; i++){
if(numsS[i] != numsT[i])
return (char)i;
}
return ' ';
}
}
代码部分三(3ms 100%)
class Solution {
public char findTheDifference(String s, String t) {
char res = 0;
for (char c: s.toCharArray()) {
res = (char) (res^c);
}
for (char c: t.toCharArray()) {
res = (char) (res^c);
}
return res;
}
}