您的位置:首页 > Web前端

LeetCode - 389. Find the Difference

2017-09-07 21:09 393 查看
Q:

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.


A:

class Solution(object):
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
sDic = {}
for ch in s:
sDic[ch] = sDic.get(ch, 0) + 1
for ch in t:
if sDic.get(ch, 0) == 0:
return ch
else:
sDic[ch] -= 1


主要思路:

先for遍历字符串s,统计每个字母出现的次数(sDic.get(ch, 0)当字典中无该键时,自动创建并取值为0);

之后便是遍历字符串t,若遍历到的字符并不在字典当中,也就是新添加的字母,这时给它默认为0(sDic.get(ch, 0)),则值为0时返回此字符;

若遍历的字母在字典中,则在其值上减去1,若新添加的字母与之前字符串中有重复,则会出现该字符值不断减1后到达0,还有一个该字母,这时因其值已经等于0,返回。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode