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中的元素,剩下的即为所求元素。这个可以接受,但是只击败了5.48%Python的答案。可见很不优。
考虑到两个字符串里面只有一个不同,一开始想到使用异或处理,不过下面怎么继续有点不是很清楚。后来看了别人的答案,原来可以和ord以及chr函数搭配使用。ord()函数是chr()函数(对于8位的ASCII字符串)或unichr()函数(对于Unicode对象)的配对函数,它以一个字符(长度为1的字符串)作为参数,返回对应的ASCII数值,或者Unicode数值。可以分别对s和t进行操作,也可以对s+t进行操作。
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
class Solution(object):
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
l1, l2 = list(s), list(t)
for e in l1:
l2.remove(e)
return "".join(l2)
# return "".join([ele for ele in t if ele not in s])
def findTheDifference2(self, s, t):
code = 0
for ch in s:
code ^= ord(ch)
for ch in t:
code ^= ord(ch)
return chr(code)
def findTheDifference3(self, s, t):
ans = 0
for c in s+t:
ans ^= ord(c)
return chr(ans)
if __name__ == '__main__':
sol = Solution()
s = "abcd"
t = "abcde"
print sol.findTheDifference(s, t)
print sol.findTheDifference2(s, t)