close

來練習一個題目吧。


[題目]

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.

ex: 

Input:
s = "abcd"
t = "abcde"

Output:
e

Explanation:
'e' is the letter that was added.

[解法]

已下是我寫的code,如果有其他不同的解法,希望大家分享出來,讓彼此的功力變強喔。

char findTheDifference(string s, string t)

{

             char ans=0;
    
             for(char a:s)
                    ans = ans ^ a;
        
             for(char a:t)
                   ans = ans ^ a;
        
             return char(ans);        
    }


[心得]

這個解答會用到幾個觀念,包含有 C++ Range-based for Statement 以及 邏輯運算子 (^: XOR)。
老實說Range-based這個東西,我也是第一次看到,真是學了一招。



[引用]

leetcode:

https://leetcode.com/problems/find-the-difference/

MSDN:

https://msdn.microsoft.com/en-us/library/b80153d8.aspx

arrow
arrow

    SouthOcean929 發表在 痞客邦 留言(0) 人氣()