您的位置:首页 > Web前端

leetcode-389. Find the Difference 字典,查找某个元素a不在list中

2016-10-12 11:26 423 查看
题目:

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,但元素的位置随机。现在在t中随机插入一个字符,请找出插入的这个字符。

代码:

class Solution(object):

    def findTheDifference(self, s, t):

        """

        :type s: str

        :type t: str

        :rtype: str

        """

        

        dict_s = dict();

        dict_t = dict();

        

        for x in s:

            dict_s[x] = 0

        for x in s:

            dict_s[x] = dict_s[x] + 1

        for x in t:

            dict_t[x] = 0

        for x in t:

            dict_t[x] = dict_t[x] + 1

            

        for x in t:

           if x not in s:

               return x

           else:

               if dict_t[x] != dict_s[x]:

                   return x

笔记:

网上看了别人的思路,发现将s、t链接起来,用异或操作也很简单。

原来,用python实现某个list s中不含元素a,直接用 if a not in s: 就可以实现,学到了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: