[LeetCode] Challenge log 389

389. Find the Difference

Best solution is to use bitwise operation XOR: same ele will be cancel if xor twice.


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:

1
2
3
4
5
6
7
8
9
Input:
s = "abcd"
t = "abcde"

Output:
e

Explanation:
'e' is the letter that was added.

Soulution:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution:
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
count = {}
for i in s:
if i not in count:
count[i] = 1
else:
count[i] += 1
for i in t:
if i not in count:
return i
else:
count[i] -= 1
for key in count:
if count[key] < 0:
return key
1
2
3
4
5
6
7
8
9
10
11
class Solution:
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
res = 0
for i in s + t:
res ^= ord(i)
return chr(res)
0%