Skip to main content

389 Find the Difference

Leetcode

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"

可以用一个 int[26] 数组储存每个字符出现多少次。但还有更简单的方法:计算两个字符串所有 char 的和,差值为多出的字符。

public char findTheDifference(String s, String t) {
char c=0;
for(int i=0;i<s.length();++i){
c+=t.charAt(i)-s.charAt(i);
}
return c+=t.charAt(t.length()-1);
}
class Solution {
public:
char findTheDifference(string s, string t) {
char c=0;
for(int i=0;i<s.length();++i){
c+=t[i]-s[i];
}
return c+t[t.length()-1];
}
};
class Solution:
def findTheDifference(self, s: str, t: str) -> str:
total = 0
for i in range(len(s)):
total += ord(t[i]) - ord(s[i])
return chr(total + ord(t[-1]))