【LeetCode】389 Find the Difference(java)

原题

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:
e

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

题目要求

题目叫“找出不同点”,题目本身也比较简单。有两个字符串s和t,它们只包含小写的字母。字符串t是由字符串s产生的,只比s多一个字母。题目的目的就是要找出这个多出的字母。

解法

解法一:这种解法比较直接,建立以个map对应字符串s,key为字符,value就是该字符出现的次数。首先遍历字符串s,来建立这个map,然后再遍历字符串t。对t中出现的每个字符,都从map中减一,当value值小于0时,则说明该字符就是多出的字符。代码我就不列出来了,这种解法和第二种类似,大家看了第二种解法就明白了。

解法二:第一种解法的map有点太重了,而且涉及到Character和char,int和Integer之间的转换,我也不喜欢。所以,我就用了另一种很类似的方法——int数组来代替map。因为字符串只有小写字母,也就是只有26中可能,那么建立一个int[16]的数组即可,索引就是字符char-'a',而数组值就是字符出现在字符串s中的次数。说白了,和解法二思路一致。代码如下:

public char findTheDifference(String s, String t) {
    int[] nums = new int[26];
    for (int i = 0; i < s.length(); i++) {
        char ch = s.charAt(i);
        ++nums[ch - 'a'];
    }
    char ret = 'a';
    for (int i = 0; i < t.length(); i++) {
        char ch = t.charAt(i);
        --nums[ch - 'a'];
        if (nums[ch - 'a'] < 0) {
            ret = ch;
            break;
        }
    }
    return ret;
}

解法三:由于字符串t只比字符串s多了一个字符,那么直接用t中所有字符值的和减去字符串s中字符值的和即可。

public char findTheDifference(String s, String t) {
    int ret = 0;
    for (int i = 0; i < s.length(); i++) {
        ret -= (int)s.charAt(i);
    }
    for (int i = 0; i < t.length(); i++) {
        ret += (int)t.charAt(i);
    }
    return (char)ret;
}

解法四:另外一种思路,既然字符串t只比字符串s多了一个字符,也就是说大部分字符都是相同的。那么,我们可以使用异或的方式,来找出这个不同的值。

public char findTheDifference(String s, String t) {
    int ret = 0;
    for (int i = 0; i < s.length(); i++) {
        ret ^= s.charAt(i);
    }
    for (int i = 0; i < t.length(); i++) {
        ret ^= t.charAt(i);
    }
    return (char)ret;
}
原文地址:https://www.cnblogs.com/styshoo/p/5922397.html