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);
    }
}
相关文章
相关标签/搜索