389. Find the Difference

Given two stringssandtwhich consist of only lowercase letters.

Stringtis generated by random shuffling stringsand then add one more letter at a random position.

Find the letter that was added int.

Example:

Input:
s = "abcd"
t = "abcde"

Output:
e

Explanation:
'e' is the letter that was added.
题目大意是给定两个字符串s和t,t是由s打乱组合而成,并随机插入一个字母。找到这个添加的字母
可以将字符串的每一个字母放入集合中,求两个集合的差集,可是...这样是不对的,题目又没说添加的字母是否出现过。仍然可以沿用求差的思想,不过是字符ASCII值的差。
代码如下:
public class Solution {
    public char findTheDifference(String s, String t) {
        int charCodeS = 0, charCodeT = 0;
        for (int i = 0; i < s.length(); ++i) charCodeS += (int)s.charAt(i);
        for (int i = 0; i < t.length(); ++i) charCodeT += (int)t.charAt(i);
        return (char)(charCodeT - charCodeS);
    }
}

 

分别对两个字符串进行遍历,s和t的长度只差1,可以对上面代码小小的优化,使用一个for循环
public char findTheDifference(String s, String t) {
        int b=0;
        for(int i = 0; i < t.length();i++) 
        {
            b += (int)t.charAt(i);
            if(i < s.length())
                b -= (int)s.charAt(i);
        }   
        return (char)b;
    }

 

 
 

posted on 2017-09-26 19:11  Wanna_Go  阅读(178)  评论(0编辑  收藏  举报

导航