389. Find the Difference

problem

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.
  • t字符串包含元素为: 字符串s加一个字符(随机生成)

    注意可能会有重合元素比如 t = 'aa ; s = 'a'

solution

  • 错误解

    转换为集合利用集合的函数difference, 集合会去重,不能处理包含重复元素的情况

class Solution(object):
    def findTheDifference(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: str
        """
        return set(t).difference(set(s)).pop()
  • 重做
class Solution(object):
    def findTheDifference(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: str
        """
        t = list(t)
        for i in s:
            if i in t:
                t.remove(i)
        
        return t[0]    
            

discuss

  • 用collectons.Counter
class Solution(object):
    def findTheDifference(self, s, t):
        return list((collections.Counter(t) - collections.Counter(s)))[0]
  • 用sorted() 然后切片

  • 用operator.xor:

    xor(a,b) 等同于a ^ b

    中^是位异或运算,即将a与b的对应位进行异或运算,同为0或者同为1时,对应位结果为0;否则为1。

class Solution(object):
    def findTheDifference(self, s, t):
        return chr(reduce(operator.xor, map(ord, s + t)))
posted @ 2016-11-21 10:43  Salmd  阅读(124)  评论(0)    收藏  举报