035 · Find the Difference

algorithm
Published

June 11, 2026

Problem

给定两个字符串 st

字符串 t 是由字符串 s 随机打乱之后,再额外加入一个字符得到的。

请返回:这个额外加入的字符。

例如:

s = "abcd"
t = "abcde"

ts 多了一个字符 "e",所以答案是:

"e"

注意,t 里的字符顺序不一定和 s 一样。你不能只比较同一个下标上的字符,因为字符可能已经被重新排列过。

Examples

示例 1

Input:  s = "abcd", t = "abcde"
Output: "e"

解释:t 中多出了字符 "e"

示例 2

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

解释:s 是空字符串,所以 t 中唯一的字符 "y" 就是额外加入的字符。

示例 3

Input:  s = "a", t = "aa"
Output: "a"

解释:s 里有一个 "a"t 里有两个 "a",所以额外加入的字符也是 "a"

Constraints

  • \(0 \leq\) s.length \(\leq 1000\)
  • t.length == s.length + 1
  • st 只由小写英文字母组成