1. 题目

2. 解答

2.1. 方法一

将 s 和 t 转化为 Python 的列表,然后遍历列表 s 的元素,将它们从列表 t 中删除,最后列表 t 中会余下一个元素,即为所求

class Solution:
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
s_list = list(s)
t_list = list(t)
for i in s_list:
t_list.remove(i)
return t_list[0]

2.2. 方法二

将 t 转化为 Python 的集合,由于集合元素的互异性,这个过程会去掉重复元素,然后再将其转化为列表 r,此时 r 包含 t 中的所有字符。

遍历 r 中的字符,然后分别计数其在 s 和 t 中出现的次数,如果二者不相等,则当前字符即为所求

class Solution:
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
""" r = list(set(t))
result = ' '
for i in r:
if s.count(i) != t.count(i):
result = i
return result

2.3. 方法三

t 中所有字符的 ASCII 码之和减去 s 中所有字符的 ASCII 码之和,最后的差对应的字符即为所求。

class Solution {
public:
char findTheDifference(string s, string t) { int count = 0; string::iterator i1 = s.begin(), i2 = t.begin(); for (; i1 != s.end() && i2 != t.end(); i1++, i2++)
{
count += *i2 - *i1;
} count = count + *i2; return char(count); }
};

2.4. 方法四

利用按位异或运算。假设有两个数 a, b,按位异或可以实现两个数的交换。

a = a ^ b
b = a ^ b = a ^ b ^ b = a ^ 0 = a
a = a ^ b = a ^ b ^ a = b

因此,我们可以将 s 和 t 中的元素按位异或,相同的元素按位异或之后都会变成零,最后的结果即为所求。

class Solution {
public:
char findTheDifference(string s, string t) { int count = 0; string::iterator i1 = s.begin(), i2 = t.begin(); for (; i1 != s.end() && i2 != t.end(); i1++, i2++)
{
count = *i2 ^ *i1 ^ count;
} count = count ^ *i2; return char(count); }
};

获取更多精彩,请关注「seniusen」!

最新文章

  1. repcache实现memcached主从
  2. PIC XC8 EEPROM操作
  3. C++知识点
  4. Windows Internals学习笔记(七)Image Loader
  5. 终端环境之tmux
  6. selenium更改readonly属性
  7. 误删除了mssql的表。 使用命令:drop table xxxx
  8. 《Linux与Qt程序设计》知识框架
  9. Ubuntu 关闭锁屏界面的 on-screen keyboard
  10. 常用ASCII 码对照表
  11. Entity Framework学习 - 2.增删改查
  12. CentOS6.3安装VBoxAdditions
  13. Adrnoid开发系列(二十五):使用AlertDialog创建各种类型的对话框
  14. mysql5.7-Group Replication
  15. 2018-2019-2 20165337《网络攻防技术》Exp5 MSF基础应用
  16. javascript--实现几个简单的操作
  17. XML文件的读取
  18. selenium 3.0变化
  19. sql server 2008 身份验证失败 18456
  20. WebGL编程指南案例解析之绘制四边形

热门文章

  1. 【题解】洛谷P2426删数
  2. svn cleanup failed–previous operation has not finished; run cleanup if it was interrupted
  3. asp.net mvc Post上传文件大小限制 (转载)
  4. select选中的值改变另一个input的值
  5. JavaScript基础-----数组(Array)
  6. springboot2.04+mybatis-plus+swagger2+CodeGenerator
  7. javascript 中数组的创建 添加 与将数组转换成字符串 页面三种提交请求的方式
  8. view围绕圆心自转
  9. 树莓派官方推荐的VNC Viewer配置详解Raspberry Pi3 B+
  10. ethereum(以太坊)(基础)--容易忽略的坑(二)