389. Find the Difference

Posted Wanna_Go

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
    }

 

 
 

以上是关于389. Find the Difference的主要内容,如果未能解决你的问题,请参考以下文章

389. Find the Difference

389. Find the Difference

389. Find the Difference

LeetCode 389. Find the Difference

Leetcode 389 Find the difference

LeetCode 389. Find the Difference