[LeetCode] Find the Difference 尋找不同


 

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

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM