389. Find the Difference
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 Explanation: 'e' is the letter that was added.
题意:
找出两个字符串中不同的那个字母
算法思路:
因为两个字符串只差一个字母,所以可以把两个字符串的每个字符求和之后相减,然后就可以得到多出的那一个
代码实现:
package easy;
public class FindtheDifference {
public static char findTheDifference(String s, String t) {
int temp=0;
for(int i=0; i<t.length(); i++){
temp += t.charAt(i);
}
for(int i=0; i<s.length(); i++){
temp -= s.charAt(i);
}
char result = (char)temp;
return result;
}
public static void main(String[] args) {
char re = findTheDifference("abcd", "abcde");
System.out.println(re);
}
}