0389. Find the Difference (E)

Find the Difference (E)

題目

Given two strings s and t which consist of only lowercase letters.java

String t is generated by random shuffling string s and then add one more letter at a random position.dom

Find the letter that was added in t.code

Example:字符串

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

Output:
e

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

題意

字符串t由字符串s亂序後加入一個隨機字母獲得,求這個隨機的字母。string

思路

直接hash記錄每一個字符的個數在進行比較。hash


代碼實現

Java

class Solution {
    public char findTheDifference(String s, String t) {
        int[] hash = new int[26];
        for (char c : s.toCharArray()) {
            hash[c - 'a']++;
        }
        for (char c : t.toCharArray()) {
            hash[c - 'a']--;
        }
        int i = 0;
        while (hash[i] == 0) {
            i++;
        }
        return (char)('a' + i);
    }
}
相關文章
相關標籤/搜索