389. Find the Difference

原題網址:https://leetcode.com/problems/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.

方法:直方圖頻率統計。

public class Solution {
    private int[] frequency(String s) {
        int[] f = new int[26];
        char[] sa = s.toCharArray();
        for(char c : sa) {
            f[c - 'a'] ++;
        }
        return f;
    }
    public char findTheDifference(String s, String t) {
        int[] fs = frequency(s);
        int[] ft = frequency(t);
        for(int i = 0; i < fs.length; i++) {
            if (fs[i] != ft[i]) {
                return (char)('a' + i);
            }
        }
        return (char)0;
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章