题目
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字符信息,再遍历t
- 两个字符串相加,将其中字符转化为编码数值进行位异或运算
解答
py
dict:
class Solution(object):
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
dc = {}
for i in s:
dc[i] = dc.get(i,0) + 1
for j in t:
if j not in dc or not dc[j]:
return j
dc[j] -= 1
xor:
class Solution(object):
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
dif = 0;
for c in s+t:
dif ^= ord(c) # 强类型
return chr(dif)
C#
public class Solution {
public char FindTheDifference(string s, string t) {
char diff = '\u0000'; // 空字符
foreach(char c in s+t)
{
diff ^= c; // 弱类型
}
return diff;
}
}