forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
find-the-difference.py
64 lines (54 loc) · 1.4 KB
/
find-the-difference.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
from __future__ import print_function
# Time: O(n)
# Space: O(1)
# 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.
import operator
import collections
from functools import reduce
class Solution(object):
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
return chr(reduce(operator.xor, map(ord, s), 0) ^ reduce(operator.xor, map(ord, t), 0))
def findTheDifference2(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
t = list(t)
s = list(s)
for i in s:
t.remove(i)
return t[0]
def findTheDifference3(self, s, t):
return chr(reduce(operator.xor, map(ord, s + t)))
def findTheDifference4(self, s, t):
return list((collections.Counter(t) - collections.Counter(s)))[0]
def findTheDifference5(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]
if __name__ == '__main__':
s = Solution()
r = s.findTheDifference2('abcd', 'abcde')
print(r)