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.
這道題給了我們兩個字符串s和t,t是在s的任意一個地方加上了一個字符,讓我們找出新加上的那個字符。這道題確實不是一道難題,首先第一反應的方法就是用哈希表來建立字符和個數之間的映射,如果在遍歷t的時候某個映射值小於0了,那麼返回該字符即可,參見代碼如下:
解法一:
class Solution { public: char findTheDifference(string s, string t) { unordered_map<char, int> m; for (char c : s) ++m[c]; for (char c : t) { if (--m[c] < 0) return c; } return 0; } };
我們也可以使用位操作Bit Manipulation來做,利用異或的性質,相同位返回0,這樣相同的字符都抵消了,剩下的就是後加的那個字符,參見代碼如下:
解法二:
class Solution { public: char findTheDifference(string s, string t) { char res = 0; for (char c : s) res ^= c; for (char c : t) res ^= c; return res; } };
我們也可以直接用加和減,相同的字符一減一加也抵消了,剩下的就是後加的那個字符,參見代碼如下:
解法三:
class Solution { public: char findTheDifference(string s, string t) { char res = 0; for (char c : s) res -= c; for (char c : t) res += c; return res; } };
下面這種方法是史蒂芬大神提出來的,利用了STL的accumulate函數,實際上是上面解法二的改寫,一行就寫完了真是喪心病狂啊,參見代碼如下:
解法四:
class Solution { public: char findTheDifference(string s, string t) { return accumulate(begin(s), end(s += t), 0, bit_xor<int>()); } };
參考資料:
https://discuss.leetcode.com/topic/55987/java-c-1-liner
https://discuss.leetcode.com/topic/55960/two-java-solutions-using-xor-sum
https://discuss.leetcode.com/topic/55912/java-solution-using-bit-manipulation