作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


[LeetCode]

https://leetcode.com/problems/find-the-difference/

  • Difficulty: Easy

题目描述

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打乱顺序之后,又随机添加了一个字符,求这个字符。

解题方法

方法一:字典统计次数

题目没有要求空间复杂度,因此可以用HashTable记录每个元素出现的次数,最后只出现了一次的就是那个被添加上去的元素。不提。

另外,可以用一个数组,把两个字符串中出现了的字符对应到数组当中,把s数组对应位置++,t对应位置–,出现了两次的元素则会抵消,否则,就是出现了一次的。

java解法如下:

public class Solution {
public char findTheDifference(String s, String t) {
int[] chars=new int[26];
for(int i=0; i<s.length(); i++){
chars[s.charAt(i) - 'a']++;
}
for(int i=0; i<t.length(); i++){
chars[t.charAt(i) - 'a']--;
}
for(int i=0; i<chars.length; i++){
if(chars[i]!=0){
return (char) ('a' + i);
}
}
return '0';
}
}

AC:9ms

python写法如下:

class Solution:
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
scount, tcount = collections.Counter(s), collections.Counter(t)
for t in tcount:
if tcount[t] > scount[t]:
return t

方法二:异或

想到了之前做的那个题,数组中其余元素出现了两次,找出数组中只出现了一次的那个数字。完完全全一样的题目。

方法是异或运算。

public class Solution {
public char findTheDifference(String s, String t) {
int answer = 0;
for(int i=0; i<s.length(); i++){
answer ^= s.charAt(i) - 'a';
}
for(int i=0; i<t.length(); i++){
answer ^= t.charAt(i) - 'a';
}
return (char) ('a' + answer);
}
}

AC:9ms

python写法如下:

class Solution(object):
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
return chr(reduce(lambda x, y : x ^ y, map(ord, s + t)))

方法三:排序

把字符串转成了列表,然后进行排序,从前向后遍历slist,如果tlist的该位置和slist不同,那么这个就是tlist添加出来的字符。如果遍历结束没有找到,那么tlist最后的字符就是答案。

class Solution:
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
slist, tlist = list(s), list(t)
slist.sort()
tlist.sort()
for i in range(len(slist)):
if slist[i] != tlist[i]:
return tlist[i]
return tlist[-1]

日期

2017 年 1 月 7 日
2018 年 11 月 10 日 —— 这么快就到双十一了??

最新文章

  1. eclipse不能新建server
  2. 修改Oracle数据库用户的密码
  3. 第三篇:GPU 并行编程的运算架构
  4. Fragment与Activity相互传递数据:
  5. 利用apache组件实现文件上传
  6. ABP框架源码学习之修改默认数据库表前缀或表名称
  7. ASP.NET Core 项目实战(持续更新~~~)
  8. SOUI开发应用展示2
  9. OO的奇妙冒险1
  10. Springboot Session集群处理
  11. 继上篇后的Excel批量数据导入
  12. arcgis 要素服务增删改查
  13. SQL-2 查找入职员工时间排名倒数第三的员工所有信息
  14. ARP欺骗防御工具arpon
  15. 【ActiveMQ入门-10】ActiveMQ学习-通配符+异步接收
  16. iPhoneX设计尺寸和适配
  17. centos安装图形操作界面
  18. jenkins 分布式部署
  19. python list 列表
  20. WCF安全 z

热门文章

  1. shell 除法和格式化输出printf
  2. 【模板】二分图最大匹配(匈牙利算法)/洛谷P3386
  3. DOTA数据集
  4. absent, absolute
  5. acute
  6. Identity Server 4 从入门到落地(八)—— .Net Framework 客户端
  7. fastJson序列化
  8. Output of C++ Program | Set 2
  9. github单独下载某一个文件夹
  10. OpenStack之一:初始化环境