p389

LeetCode p389 Find the Difference 题解

1.题目:

Given two strings s and t which consist of only lowercase letters.
String t is generated by random shuffling string s and then add one more letter at a random position.
Find the letter that was added in t.
Example:
Input:
s = “abcd”
t = “abcde”
Output:
e

题意:

输入两个字符串,第一个字符串比第二个字符串少一个字符,返回那个字符。

2.解题思路:

见代码

3.代码


[title] [] [url] [link text]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 
public class Solution {
public char findTheDifference(String s, String t) {
char ans='a';
int sum=0;
for (int i=0;i<s.length();i++)
{
sum=sum+(t.charAt(i)-'a');
sum=sum-(s.charAt(i)-'a');
}
sum=sum+(t.charAt(t.length()-1)-'a');
ans=(char) ('a'+sum);
return ans;
}
}


4.一些总结: