LeetCode389-找不同

题目链接

英文链接:https://leetcode.com/problems/find-the-difference/

中文链接:https://leetcode-cn.com/problems/find-the-difference/

题目详述

给定两个字符串 st,它们只包含小写字母。

字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。

请找出在 t 中被添加的字母。

示例:

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

输出:
e

解释:
'e' 是那个被添加的字母。

题目详解

  • 运用位运算,两个同样的值异或的结果为 0。
  • 对两个字符串中的所有字符进行异或,得到的结果就是被添加的字符。
1
2
3
4
5
6
7
8
9
10
11
12
13
public class LeetCode_00389 {

public char findTheDifference(String s, String t) {
char res = 0;
for (char c : s.toCharArray()) {
res ^= c;
}
for (char c : t.toCharArray()) {
res ^= c;
}
return res;
}
}