LeetCode

来源:互联网 发布:淘宝店铺运营推广方案 编辑:程序博客网 时间:2024/06/15 14:25

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:eExplanation:'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,返回。

原创粉丝点击