【leetcode】389. Find the Difference【E】

原创 2016年08月31日 09:56:33

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.

Subscribe to see which companies asked this question

最开始想都没想就用了set,结果肯定是不对的啊,因为集合会去重,要是有两个a,就变成一个a了

所以用字典,记录每个字母的个数

有一个小技巧,就是使用字典里面的get

还有就是检查的时候,使用try,这样就不用单独处理keyerror了



class Solution(object):
    def findTheDifference(self, s, t):

        dic_s = dict()
        dic_t = dict()

        for i in s:
            dic_s[i] = dic_s.get(i,0) + 1

        for i in t:
            dic_t[i] = dic_t.get(i,0) + 1

        for i in t:
            #print i
            try:
                if dic_t[i] != dic_s[i]:
                    return i

            except:
                return i


        """
        :type s: str
        :type t: str
        :rtype: str
        """



相关文章推荐

【LeetCode-94】Binary Tree Inorder Traversal(C++)

题目要求:完成二叉树的中序遍历。 解题方法: 1.递归。 /** * Definition for a binary tree node. * struct TreeNode { * ...

leetcode题解-566. Reshape the Matrix && 495. Teemo Attacking

566,题目:In MATLAB, there is a very useful function called 'reshape', which can reshape a matrix into ...

LeetCode笔记:389. Find the Difference

在两个字符串中找出唯一多出的那个字母

LeetCode 389. Find the Difference

题意两个字符串s,t,都是小写字母,t由s中的字符和新增的一个字母随机排列组合而成,找出新增的字符!思路最直接的思路是HashMap,根据字符串s建立一个HashMap,key是字母,value是字母...

leetcode389. Find the Difference

389. Find the DifferenceGiven two strings s and t which consist of only lowercase letters.String t i...

leetcode算法——389. Find the Difference(基于JAVA)

Given two strings s and t which consist of only lowercase letters. String t is generated by random s...

【LeetCode】389 Find the Difference(java)

原题Given two strings s and t which consist of only lowercase letters.String t is generated by random ...
  • styshoo
  • styshoo
  • 2016年09月29日 23:46
  • 485

[LeetCode]389. Find the Difference(找不同)

389. Find the DifferenceGiven two strings s and t which consist of only lowercase letters. String t...

[LeetCode]242.Valid Anagram&383. Ransom Note&389. Find the Difference

242.Valid Anagram 383. Ransom Note 389. Find the Difference

【Leetcode】389. Find the Difference

方法一: 思路: 利用一个HashMap,先统计s字符串中每个字符出现的次数,然后遍历t字符串,若该字符未包含在HashMap中或出现次数等于0,立即返回该字符,否则,该字符出现的次数减一。 pub...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:【leetcode】389. Find the Difference【E】
举报原因:
原因补充:

(最多只允许输入30个字)