Find the Difference (E)

题目

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.

题意

字符串t由字符串s乱序后加入一个随机字母得到,求这个随机的字母。

思路

直接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);
    }
}
内容来源于网络如有侵权请私信删除

文章来源: 博客园

原文链接: https://www.cnblogs.com/mapoos/p/13726598.html

你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!