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++
Java
解法2:O(N) Time Complexity with O(1) Space
找不同的题目可以尝试用抵消的思路。一个抵消的工具就是XOR,如果对每一个字符进行异或操作,由于相同的元素抵消,剩下的一定是不相同的那一个。
C++