LeetCode_389.找不同

给定两个字符串 st,它们只包含小写字母。

字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。

请找出在 t 中被添加的字母。

示例 1:

输入:s = "abcd", t = "abcde"
输出:"e"
解释:'e' 是那个被添加的字母。

示例 2:

输入:s = "", t = "y"
输出:"y"

示例 3:

输入:s = "a", t = "aa"
输出:"a"

示例 4:

输入:s = "ae", t = "aea"
输出:"a"

提示:

  • 0 <= s.length <= 1000
  • t.length == s.length + 1
  • st 只包含小写字母

C#代码

public class Solution {
    public char FindTheDifference(string s, string t) {
        Dictionary<char,int> dic =new Dictionary<char,int>();
        for(int i = 0; i< s.Length; i++){
            if(dic.ContainsKey(s[i])) dic[s[i]] += 1;
            else dic.Add(s[i], 1);
        }

        for(int i = 0; i < t.Length; i++){
            if(!dic.ContainsKey(t[i])) return t[i];
            else if(dic[t[i]] == 1) dic.Remove(t[i]);
            else dic[t[i]] -= 1;
        }

        return ' ';
    }
}
原文地址:https://www.cnblogs.com/fuxuyang/p/14244642.html