题目:
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.
题目
解法1:
先排序,然后找到第一个不同的,如果找不到,则返回长的那一个的最后一个元素。(太慢)
python代码:
class Solution(object):
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
s_sorted=sorted(s)
t_sorted=sorted(t)
for i in range(len(s_sorted)):
if s_sorted[i]!=t_sorted[i]:
return t_sorted[i]
return t_sorted[-1]
解法2:
数两个字符串中各个字母出现的个数,返回个数不同的那个字母。(python中用Counter)
python代码:
from collections import Counter
class Solution(object):
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
count_s=Counter(s)
count_t=Counter(t)
for key in count_t:
if key not in count_s or count_t[key]!=count_s[key]:
return key
解法3:
这题类似于Single Number I 所以可以用异或做(震惊了)。
速度快的都是用异或做的。
python代码:
class Solution(object):
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
init=0
for _s in s:
init^=ord(_s)
for _t in t:
init^=ord(_t)
return chr(init)
c++代码:
class Solution {
public:
char findTheDifference(string s, string t) {
int init=0;
for (auto _s:s)
init^=_s;
for (auto _t:t)
init^=_t;
return (char)init;
}
};
总结:
可以用字典计数的做法,或者用异或,这题居然可以用异或做,简直震惊,所以做题的时候要合理联想啊!
发现一件事:代码一样的情况下,python导入包居然多花了10ms!