389. Find the Difference

389. Find the Difference

一、題目

You are given two strings s and t.

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

Return the letter that was added to t.

 

Example 1:

Input: s = "abcd", t = "abcde" Output: "e" Explanation: 'e' is the letter that was added.

Example 2:

Input: s = "", t = "y" Output: "y"

 

Constraints:

  • 0 <= s.length <= 1000
  • t.length == s.length + 1
  • s and t consist of lowercase English letters.

 

二、程式作法

public class Solution
{
    public char FindTheDifference(string s, string t)
    {
        int[] ss = new int[26];
        for (int i = 0; i < 26; i++)
            ss[i] = 0;
        for (int i = 0; i < s.Length; i++)
            ss[s[i] - 'a']++;
        for (int i = 0; i < t.Length; i++)
        {
            if (ss[t[i] - 'a'] == 0) return t[i];
            ss[t[i] - 'a']--;
        }
        return '?';
    }
}

 

三、思路筆記

string s 只會比 string t 少一個字元,而 t 大部份字元內容都來自 string s 隨機取得,

只差一字元,從 t 中找出該字元。