关于异或特点的一些应用

因为异或有以下的特点:
一个数与0异或等于它本身:a ^ 0 = a
一个数与另一个数异或两次等于这个数本身:(a ^b) ^b = a
LeetCode.136.只出现一次的数
给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。

示例 1:

输入: [2,2,1]
输出: 1
示例 2:

输入: [4,1,2,1,2]
输出: 4

利用异或的思想来做这个题

class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        a = 0
        for num in nums:
            a ^= num
        return a

389.找不同
给定两个字符串 s 和 t,它们只包含小写字母。

字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。

请找出在 t 中被添加的字母。

输入:
s = "abcd"
t = "abcde"

输出:
e

解释:
'e' 是那个被添加的字母。

同样利用异或的思想:
用0和字符串s和t的每一个字符异或,同样的字符以偶数个数出现,与0异或偶数次还是0,0与加入的字符,它的次数一定是奇数个,与0异或就是这个字符。

  • 注意字符与它的ASCII码的转换
class Solution(object):
    def findTheDifference(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: str
        """
        char = 0
        for chars in s:
            char ^= ord(chars) - 97  
        for chart in t:
            char ^= ord(chart) - 97
        return chr(char+97)

这个题还有另一种解法:就是利用count()函数统计字符出现的次数。

class Solution(object):
    def findTheDifference(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: str
        """
        for char in t:
            if s.count(char) != t.count(char):
                return char

猜你喜欢

转载自blog.csdn.net/qq_20966795/article/details/85724270
今日推荐