# 389. Find the Difference 找不同

@TOC

[LeetCode]

https://leetcode.com/problems/find-the-difference/open in new window

• Difficulty: Easy

## # 题目描述

Given two strings `s` and `t` which consist of only lowercase letters.

String `t` is generated by random shuffling string `s` and then add one more letter at a random position.

Find the letter that was added in `t`.

Example:

``````Input:
s = "abcd"
t = "abcde"

Output:
e

Explanation:
'e' is the letter that was added.
``````

## # 解题方法

### # 方法一：字典统计次数

java解法如下：

``````public class Solution {
public char findTheDifference(String s, String t) {
int[] chars=new int[26];
for(int i=0; i<s.length(); i++){
chars[s.charAt(i) - 'a']++;
}
for(int i=0; i<t.length(); i++){
chars[t.charAt(i) - 'a']--;
}
for(int i=0; i<chars.length; i++){
if(chars[i]!=0){
return (char) ('a' + i);
}
}
return '0';
}
}
``````

AC:9ms

python写法如下：

``````class Solution:
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
scount, tcount = collections.Counter(s), collections.Counter(t)
for t in tcount:
if tcount[t] > scount[t]:
return t
``````

### # 方法二：异或

``````public class Solution {
public char findTheDifference(String s, String t) {
for(int i=0; i<s.length(); i++){
}
for(int i=0; i<t.length(); i++){
}
}
}
``````

AC:9ms

python写法如下：

``````class Solution(object):
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
return chr(reduce(lambda x, y : x ^ y, map(ord, s + t)))
``````

### # 方法三：排序

``````class Solution:
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
slist, tlist = list(s), list(t)
slist.sort()
tlist.sort()
for i in range(len(slist)):
if slist[i] != tlist[i]:
return tlist[i]
return tlist[-1]
``````

## # 日期

2017 年 1 月 7 日 2018 年 11 月 10 日 —— 这么快就到双十一了？？