[leetcode]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:

1
2
3
4
5
6
7
8
9
Input:
s = "abcd"
t = "abcde"

Output:
e

Explanation:
'e' is the letter that was added.

解题思路与代码

这个题类似Single Number,也就是两个字符串除了一个字符以外,其他字符都是两两相等,找出只出现一次的字符。代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class  {
public char findTheDifference(String s, String t) {
char ch = 0;

for(int i = 0; i < s.length(); i++){
ch ^= s.charAt(i);
ch ^= t.charAt(i);
}

ch ^= t.charAt(t.length() - 1);

return ch;
}
}