389. Find the Difference
来源:互联网 发布:软件开发企业税率 编辑:程序博客网 时间:2024/06/03 08:33
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:eExplanation:'e' is the letter that was added.根据每个字符char类型对应的int值进行累加,然后相减,得到差值。
public char findTheDifference(String s, String t) { int charCodeS=0,charCodeT=0; for(int i=0;i<s.length();i++){ charCodeS +=s.charAt(i); } for(int i=0;i<t.length();i++){ charCodeT +=t.charAt(i); } return (char)(charCodeT-charCodeS); }
然后可以优化为一个for循环,直接在一个变量charCode上面加减。
public char findTheDifference(String s, String t) { int charCode=t.charAt(s.length()); for (int i = 0; i < s.length(); i++) { charCode -= (int)s.charAt(i); charCode += (int)t.charAt(i); } return (char)charCode; }取得多出那一位的char字符的int值然后按照s(少的那一个字符串)进行循环,减去s的每一个char字符值,加上每一个t的char字符值。最后得到结果转换回char,即可以得到结果。
还有一个桶排序,没想明白。
0 0
- 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
- 有序二维数组的查找
- 通过动态面板实现列表下拉自动刷新
- hdu 4857 逃生(拓扑排序)
- Python的环境搭建——Python学习笔记
- 简述PrintWriter中write()方法和print()方法的区别?
- 389. Find the Difference
- 二叉树的非递归遍历
- Dlib相关问题
- 解决android studio真机调试无法打印log的问题
- 两个surfaceview的重叠效果类似直播效果中的视频和讲义实践
- tushare搭建及python远程调试
- 802.11协议
- /bin/bash^M: bad interpreter: No such file or directory
- Linux命令系列(1):ls命令