leetcode解题: Find the Difference (389)

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.

解法1:O(N) Time Complexity with O(1) Space

用Hash的思路,对短字符串建立Hash索引,然后长字符串里面每一个字符减一,最后如果发现出现负数次数的字符时则一定是多出来的那个字符。
C++ 中注意unordered_map的用法,unordered_map::operator[] 对于不存在的元素会进行插入操作并初始化对应的map数值。
Java取字符串中的字符的method是s.charAt(i)
C++

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
char findTheDifference(string s, string t) {
std::unordered_map<char, int> strmap;
for (char c: s) ++strmap[c];
for (char c: t) {
--strmap[c];
if (strmap[c] < 0) return c;
}
return 0;
}
};

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Solution {
public char findTheDifference(String s, String t) {
int[] map = new int[26];
for (int i = 0; i < s.length(); i++) {
map[s.charAt(i) - 'a']++;
map[t.charAt(i) - 'a']--;
}
map[t.charAt(t.length() - 1) - 'a']--;
char res = 'a';
for (int i = 0; i < 26; i++) {
if (map[i] < 0) {
res += i;
break;
}
}
return res;
}
}

解法2:O(N) Time Complexity with O(1) Space

找不同的题目可以尝试用抵消的思路。一个抵消的工具就是XOR,如果对每一个字符进行异或操作,由于相同的元素抵消,剩下的一定是不相同的那一个。
C++

1
2
3
4
5
6
7
8
9
class Solution {
public:
char findTheDifference(string s, string t) {
char res = 0;
for (char c: s) res ^= c;
for (char c: s) res ^= c;
return res;
}
};