forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
find_difference.py
28 lines (25 loc) · 747 Bytes
/
find_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
"""
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.
For example:
Input:
s = "abcd"
t = "abecd"
Output: 'e'
Explanation:
'e' is the letter that was added.
"""
"""
We use the characteristic equation of XOR.
A xor B xor C = A xor C xor B
If A == C, then A xor C = 0
and then, B xor 0 = B
"""
def find_difference(s, t):
ret = 0
for ch in s + t:
# ord(ch) return an integer representing the Unicode code point of that character
ret = ret ^ ord(ch)
# chr(i) Return the string representing a character whose Unicode code point is the integer i
return chr(ret)