389. 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.
注意:
t的形成过程,随机的字母可能是s中出现的,也可能是s中没有出现的(其中可能序号在s的每个字母序号最大最小之间)
Example:
Input:
s = "abcd"
t = "abcde"
Output:
e
Explanation:
'e' is the letter that was added.
s = "abcd"
t = "abcde"
Output:
e
Explanation:
'e' is the letter that was added.
Using XOR:使用异或
注意知识点
1.异或的作用:异或有个知识点是n^n=0;0^n=0
这个知识点,在一些出现多次的数字中,只有唯一一个元素出现一次的场景非常方便,之前的single Number也是这个思路。
2.reduce和map就不说了
3.chr是0-255的数字转换为对应的字符,ord是将字符转换为对应的ASCII数字
chr(97)='a' ord('a')=97
class Solution(object):
def findTheDifference(self, s, t):
return chr(reduce(operator.xor, map(ord, s + t)))
知识点
collections.Counter(t)的作用是将一个列表或者字符串转化为一个字典,
Counter类:为hashable对象计数,是字典的子类
也可以使用Counter模块,作用是一样的,可以多在cmd中测试测试
Using
collections.Counter()
:
class Solution(object):
def findTheDifference(self, s, t):
return list((collections.Counter(t) - collections.Counter(s)))[0]
知识点:
1.字符串是可以用sorted(str)函数将每个字母排序得到一个列表的
2.zip()的作用
看例子就秒懂
x = [1, 2, 3]
y = [4, 5, 6, 7]
xy = zip(x, y)
y = [4, 5, 6, 7]
xy = zip(x, y)
print
xy
---------------------------
x = [1, 2, 3]
y = [4, 5, 6]
z = [7, 8, 9]
xyz = zip(x, y, z)
print xyz
A 2-liner here using
sorted()
:
注意这个代码的用法,强调了本题t的形成过程,随机的字母可能是s中出现的,也可能是s中没有出现的(其中可能序号在s的每个字母序号最大最小之间),
class Solution(object):
def findTheDifference(self, s, t):
s, t = sorted(s), sorted(t)
return t[-1] if s == t[:-1] else [x[1] for x in zip(s, t) if x[0] != x[1]][0]
感觉做一个题能学好多知识点啊。。。。。