leetcode389.Find The Difference

题目要求

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中出现一次相应计数加一,在t中出现一次则减一。最后只需要遍历整数数组检查是否有某个字符计数大于0。则该字符就是多余的字符。

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

思路二:求和

我们知道,字符对应的ascii码是唯一的,那么既然两个字符串相比只有一个多余的字符,那么二者的ascii码和相减就可以找到唯一的字符的ascii码。

    public char findTheDifference2(String s, String t){
        int value = 0;
        for(int i = 0 ; i<s.length() ; i++) {
            value -= s.charAt(i);
            value += t.charAt(i);
        }
        char result = (char)(value + t.charAt(t.length()-1)); 
        return result;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章