LeetCode - 389. Find the Difference - 三種不同解法 - ( C++ ) - 解題報告


1.題目大意

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.

給定兩個字符串,有其中一個字符串有一個多出來的字符,找出那個字符。這題的Example依然是給的不大好,下面再給一個example:

Input:
s = "adbc"
t = "bacde"

Output:
e

 

2.思路

這題思路比較簡單,下面提供幾個思路,第一個是我的原始思路,利用字母實際上是基於ASCII代碼,可以轉換為十進制數字來計算的。

class Solution
{
public:
    char findTheDifference(string s, string t)
    {
        int sum=0;
        char ch;
        if(s.size()>t.size()) swap(t,s); //s is the small one
        for(int i=0; i<s.size(); i++)
        {
            sum-=(s[i]);
            sum+=(t[i]);
        }
        sum+=(t[s.size()]);
        ch=(char)(sum);
        return ch;
    }
};

 第二個思路是這篇文章里的Hash表的思路,但我個人感覺過於復雜,事實上這個思路的runtime表現也很不好。

   第三個思路依然是上篇文章里的,基本想法是位運算思路,這個思路runtime跟第一個思路表現差不多,都是可以考慮的思路。


免責聲明!

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



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