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.
给出字符串s和字符串t,t比s多一个字母,找出这个字母。
思路:
利用ASCII码,把s中所有字母的ASCII码求和,t中所有ASCII码求和,它们的差值就是多出来的字母。
public char findTheDifference(String s, String t) {
if(s.length() == 0) return t.charAt(0);
int diff = 0;
int n = s.length();
for(int i = 0; i < n; i++) {
diff += t.charAt(i) - s.charAt(i);
}
diff += t.charAt(n);
return (char)diff;
}
该博客介绍了一种方法来找出两个字符串中,其中一个比另一个多出的字母。通过计算两个字符串中每个字符ASCII码的差值,可以确定在哪个位置添加了额外的字母。在给定的示例中,通过这种方法找到了字符串`t`中比`s`多出的字母`e`。
357

被折叠的 条评论
为什么被折叠?



