LeetCode 389——找不同
2024-08-25 22:20:01
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」!
最新文章
- repcache实现memcached主从
- PIC XC8 EEPROM操作
- C++知识点
- Windows Internals学习笔记(七)Image Loader
- 终端环境之tmux
- selenium更改readonly属性
- 误删除了mssql的表。 使用命令:drop table xxxx
- 《Linux与Qt程序设计》知识框架
- Ubuntu 关闭锁屏界面的 on-screen keyboard
- 常用ASCII 码对照表
- Entity Framework学习 - 2.增删改查
- CentOS6.3安装VBoxAdditions
- Adrnoid开发系列(二十五):使用AlertDialog创建各种类型的对话框
- mysql5.7-Group Replication
- 2018-2019-2 20165337《网络攻防技术》Exp5 MSF基础应用
- javascript--实现几个简单的操作
- XML文件的读取
- selenium 3.0变化
- sql server 2008 身份验证失败 18456
- WebGL编程指南案例解析之绘制四边形
热门文章
- 【题解】洛谷P2426删数
- svn cleanup failed–previous operation has not finished; run cleanup if it was interrupted
- asp.net mvc Post上传文件大小限制 (转载)
- select选中的值改变另一个input的值
- JavaScript基础-----数组(Array)
- springboot2.04+mybatis-plus+swagger2+CodeGenerator
- javascript 中数组的创建 添加 与将数组转换成字符串 页面三种提交请求的方式
- view围绕圆心自转
- 树莓派官方推荐的VNC Viewer配置详解Raspberry Pi3 B+
- ethereum(以太坊)(基础)--容易忽略的坑(二)