# \#389 Find the Difference
## *給定字串s, t, t由s調換字元順序後組成, 並額外增加了一個字元, 找到並回傳這個多出來的字元*
## Log
- build 20210720 by syhuang
## XOR兩兩排除法
- 用XOR兩兩相消, 回傳消除到最後多出來的字元
- 搭配charCodeAt()和fromCharCode()對字元做運算
```javascript=
var findTheDifference = function(s, t) {
let result = 0;
for(let i=0; i<s.length; i++){
result ^= s[i].charCodeAt();
}
for(let i=0; i<t.length; i++){
result ^= t[i].charCodeAt();
}
return String.fromCharCode(result);
};
```
## 解法2
- 用map下去做, 計算s字元出現次數後再用t去扣, 回傳沒找到or扣到0的字元
- leetcode submit runtime >95%, memory >50%
```javascript=
var findTheDifference = function(s, t) {
let map = new Map();
let result;
s.split('').forEach(function(c){
map.set(c,map.has(c)?map.get(c)+1:1);
});
try{
t.split('').forEach(function(c){
let count = map.get(c);
if(!count){
result = c;
throw {};
}else{
map.set(c,count-1);
}
});
}catch{};
return result;
};
```
## 初見
- 用t下去逐字元跑迴圈, 對每個字元去除掉s中的相同字元, 當找不到字元時就表示是多餘字元
- leetcode submit結果memory過高(>100%), runtime 80%
```javascript=
var findTheDifference = function(s, t) {
let oriStr = s;
let result;
try{
t.split('').forEach(function(c){
let cpos = oriStr.indexOf(c);
if(cpos<0){
result = c;
throw {};
}else oriStr = String.prototype.concat(oriStr.substr(0,cpos),oriStr.substr(cpos+1));
});
}catch{};
return result;
};
```
## 備註
## 參考
- [三種參考解](https://leetcode.com/problems/find-the-difference/discuss/86904/3-Different-Python-Solutions-(Dictionary-Difference-XOR))
###### tags: `leetcode`, `leetcode-easy`