您的位置:首页 > Web前端

LeetCode -- 389. Find the Difference

2016-11-21 13:44 435 查看

题目

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.

思路

  1. t比s多了一个随机字符,可用字典储存s字符信息,再遍历t
  2. 两个字符串相加,将其中字符转化为编码数值进行位异或运算

解答

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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: