package T389找不同;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class Solution {
public static char findTheDifference(String s, String t) {
Character result = null;
Map<Character, Integer> sMap = new HashMap<>();
Map<Character, Integer> tMap = new HashMap<>();
for (Character c : s.toCharArray()) {
if (!sMap.containsKey(c)) {
sMap.put(c, 0);
}
sMap.put(c, sMap.get(c) + 1);
}
for (Character c : t.toCharArray()) {
if (!tMap.containsKey(c)) {
tMap.put(c, 0);
}
tMap.put(c, tMap.get(c) + 1);
}
Set<Map.Entry<Character, Integer>> entries = tMap.entrySet();
for (Map.Entry<Character, Integer> entry : entries) {
Character key = entry.getKey();
Integer value = entry.getValue();
if (!value.equals(sMap.get(key))) {
result = key;
break;
}
}
return result;
}
}
```
import collections
class Solution:
def findTheDifference(self, s: str, t: str) -> str:
s_m = collections.Counter(s)
t_m = collections.Counter(t)
for k,v in s_m.items():
if t_m[k] == s_m[k]:
t_m.pop(k)
else:
return k
for k,_ in t_m.items():
return k
'''
python 3.2之后
collections.Counter 提供了加减方法。
Counter(t) - Counter(s)后返回值就是多出来的字母,list()后返回即可。
'''
def findTheDifference2(self, s: str, t: str) -> str:
return list(collections.Counter(t) - collections.Counter(s))[0]