LeetCode | 389. Find the Difference 字符串

Giventwo strings s and t which consist of only lowercase letters.

String t isgenerated by random shuffling string s andthen add one more letter at a random position.

Findthe letter that was added in t.

Example:

Input:

s = "abcd"

t = "abcde"

 

Output:

e

 

Explanation:

'e' is the letter that was added.

这一题可以使用两个数组,第一个数组用来存储s中每个字符的数量,第二个数组用来存储t中每个字符的数量,一旦当发现t中某个字符的数量多于s中某个字符的数量的时候,说明这个字符是插入的字符,直接返回就好了

这一题主要的知识点是,在python中,使用ord(a)可以获得字符a的ASCI值,使用chr(a)当a是整数的时候,可以获得a的ASCI值对于的整数,这一点一定要注意

classSolution(object):

    def findTheDifference(self, s, t):

        """

        :type s: str

        :type t: str

        :rtype: str

        """

        theSCheck = [0] * 27

        theTCheck = [0] * 27

        theA = ord('a')

        for i in s:

            theSCheck[ord(i) - theA] += 1

        for i in t:

            tmp = ord(i)

            theTCheck[tmp - theA] += 1

            if theTCheck[tmp - theA] >theSCheck[tmp - theA]:

                return i

        return 'a'

这一题还有一种更简单的解法,

classSolution(object):

    def findTheDifference(self, s, t):

        """

        :type s: str

        :type t: str

        :rtype: str

        """

        for i in t:

            if s.count(i) < t.count(i):

                return i

理论上来说,count的时间复杂度应该是O(N),这种方法的时间复杂度应该是O(n ^ 2)但是实际上下面这种方法比上面的方法的时间要快,我觉得可能是因为,对于python中的str而言,在创建的时间其每个字符的数量就已经知道了,查询起来可能只需要O(1)的时间,所以以后在str中统计某个字符的数量的时候,放心大胆的使用count,只需要O(1)的时间!

猜你喜欢

转载自blog.csdn.net/u012737193/article/details/80636471