题目解析: 有两个字符串s和t,s中随机插入一个字符得到t。求随机插入的字符。 例子: 输入: s = “abcd” t = “abcde”
输出: e
解法:(异或方法) class Solution(object): def findTheDifference(self, s, t): “”” :type s: str :type t: str :rtype: str “”” if len(s)+1 != len(t): return ”
return chr(reduce(operator.xor,map(ord,s+t)))
知识点总结: 核心是异或操作。异或操作是按位异或的,且与顺序无关。 chr()函数用一个范围在0~255整数作参数,返回一个对应的字符。 ord()函数是chr()函数(对于8位的ASCII字符串)或unichr()函数(对于Unicode对象)的配对函数,它以一个字符(长度为1的字符串)作为参数,返回对应的ASCII数值,是一个十进制整数。
参考文献: http://crazier9527.iteye.com/blog/411001 http://www.2cto.com/kf/201609/543954.html
转载请注明原文地址: https://ju.6miu.com/read-19054.html