题目链接
https://leetcode.com/problems/find-the-difference/
题目原文
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.
题目翻译
给定两个由小写字母构成的字符串s和t,t是由s中的所有字母随机打乱后在任一位置插入一个新字母构成的字符串。请在t中找出新加入的字母。
思路方法
思路一
分别统计s和t中每个字母出现的次数,不一样的即为所求。为了减少计算量,可以先遍历s,用数组统计26个字母出现的次数;再遍历t,在刚才的数组基础上对出现的字母次数减一,次数出现负数的字母即为所求。
代码
class Solution(object):
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
letters = [0] * 26
for c in s:
letters[ord(c) - 97] += 1
for c in t:
letters[ord(c) - 97] -= 1
if letters[ord(c) - 97] < 0:
return c
思路二
类似上面的思路,用dict实现也比较方便。
代码
class Solution(object):
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
letters = {}
for c in s:
letters[c] = letters[c] + 1 if c in letters else 1
for c in t:
if c not in letters:
return c
letters[c] -= 1
if letters[c] < 0:
return c
思路三
考虑到t是由s添加一个字母得到,那么这个添加的字母在s和t中出现的总次数一定是唯一的一个奇数。基于这个想法,用异或操作得到该字母。
代码
class Solution(object):
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
return chr(reduce(operator.xor, map(ord, s + t)))
思路四
类似思路三,除了用异或操作,还可以用加减法找到该字母。
代码
class Solution(object):
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
res = ord(t[-1])
for i in xrange(len(s)):
res = res + ord(t[i]) - ord(s[i])
return chr(res)
PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:http://blog.csdn.net/coder_orz/article/details/52387709