0%

[Leetcode]389. Find the Difference(C++)

题目描述

题目链接:389. Find the Difference

  • 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.

例子

例子 1

Input: s = "abcd", t = "abcde"
Output: "e"
Explanation: 'e' is the letter that was added.

例子 2

Input: s = "", t = "y"
Output: "y"

例子 3

Input: s = "a", t = "aa"
Output: "a"

Constraints

  • 0 <= s.length <= 1000
  • t.length == s.length + 1
  • s and t consist of lower-case English letters.

解题思路

这道题比较直观的方法是通过哈希表记录两个字符串出现过的字符然后进行比较,这里不再赘述。还有一种取巧的方法是利用异或的思路。两数进行每一位比较,相同取 0 否则取 1。具体到数字上则是两数相同异或得 0,且任何数与 0 异或不变。并且遵循交换律,即 a = c, a ^ b ^ c = a ^ c ^ b = 0 ^ b = b。由于两个字符串只有一个字符不同,因此将所有字符进行异或最后剩下的一定是不同的那个字符。代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <string>
class Solution {
public:
char findTheDifference(std::string s, std::string t) {
int val = 0;
for(auto c : s) {
val ^= c;
}
for (auto c: t) {
val ^= c;
}

return (char) val;

}
};
  • 时间复杂度: O(n)
  • 空间复杂度: O(1)

GitHub 代码同步地址: 389.FindTheDifference.cpp

其他题目:
GitHub: Leetcode-C++-Solution
博客: Leetcode-Solutions