Tutorial: 389. Find the Difference
来源:互联网 发布:增值税发票 数据接口 编辑:程序博客网 时间:2024/05/10 06:02
题目
给定两个只含有小写字母的字符串s和t。t是打乱字符顺序之后的s,而且还在其中某个随机位置添加了一个字符c。请找出这个字符c。
算法
由于t只比s多了一个字符,我们可以认为s和t中的字母是“成对出现的”。如果我们把这些字母当做数字,那么就可以用异或操作来排除所有成对出现的字母,最后的结果就是那个多出来的字母。
例如,A⊕A=0,而A⊕A⊕B=B,我们就可以用异或来找出这个多出来的字母。
代码
//由于这个算法里面有两个循环,这是一种比较慢的解决方案private char findTheDifference(String s, String t) { char result=0; for(int i=0;i<s.length();i++){ result^=s.charAt(i); } for(int j=0;j<t.length();j++){ result^=t.charAt(j); } return result;}//使用一个循环的算法,速度有明显提升private char findTheDifference(String s, String t) { char result=0; int length=(s.length()>=t.length())?t.length():s.length(); for(int i=0;i<length;i++){ result^=s.charAt(i); result^=t.charAt(i); } return (s.length()>=t.length())?(char)(result^s.charAt(s.length()-1)):(char)(result^t.charAt(t.length()-1));}
关于此文章
本文首发于作者的个人博客stormlin.com。你也扫描以下二维码来关注我的个人微信公众号来获取更多更新鲜的内容哦。
0 0
- Tutorial: 389. Find the Difference
- 389. Find the Difference
- 389. Find the Difference
- 389. Find the Difference
- 389. Find the Difference
- 389. Find the Difference
- 389. Find the Difference
- 389. Find the Difference
- 389. Find the Difference
- 389. Find the Difference
- 389. Find the Difference*
- 389. Find the Difference
- 389. Find the Difference
- 389. Find the Difference
- 389. Find the Difference
- 389. Find the Difference
- 389. Find the Difference
- 389. Find the Difference
- Shell—启用Shell脚本调试模式的方法
- AndroidStudio开发插件
- 在Linux系统上,上传文件
- HttpClient4使用(模拟登陆)
- php数组是值传递,对象是引用传递
- Tutorial: 389. Find the Difference
- 数据处理与模型选择的一些注释
- nodejs学习一
- [Android 知识点] Constraints Layout 约束布局
- U盘容量变小?这儿有解决方法!
- 利用nw.js结合h5实现创建exe文件
- 关于ArraryList排序的一点记录
- 四个document.getElement(s)By
- equals 跟hashcode 在集合中的一点知识点