389. Find the Difference

Q: 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.

问题:有两个字符串s和t,t是将s中所有字母打乱顺序并随意添加了一个字母构成的,请找出这个字母。

Example:

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

Output:
e

Explanation:
'e' is the letter that was added.


思路一:将两个字符串中的字符分别计次,然后比较字符数是否相等,不等的就是添加的字母。

代码:

    public char findTheDifference(String s, String t) {
        int cs[] = new int[26];
        int ct[] = new int[26];
        for(int i=0;i


思路二:将两个字符串转化为字符数组,然后分别按ASCII码将数组加起来,用t数组的和减去s数组的和即为所加字母的ASCII码。

代码:

    public char findTheDifference(String s, String t) {
        char[] array1 = s.toCharArray();
        char[] array2 = t.toCharArray();
        
        int asciis = 0;
        int asciit = 0;
        
        for(int i = 0; i < array1.length; i++){
            asciis += (int)array1[i];
        }
        
        for(int i = 0; i < array2.length; i++){
            asciit += (int)array2[i];
        }
        
        return (char)(asciit-asciis);
    }



你可能感兴趣的:(LeetCode)