1. 程式人生 > >【LeetCode 簡單題】86-找不同

【LeetCode 簡單題】86-找不同

宣告:

今天是第86道題。給定n,從 1 到 n 選擇一個數字。 你需要猜我選擇了哪個數字。以下所有程式碼經過樓主驗證都能在LeetCode上執行成功,程式碼也是借鑑別人的,在文末會附上參考的部落格連結,如果侵犯了博主的相關權益,請聯絡我刪除

(手動比心ღ( ´・ᴗ・` ))

正文

題目:給定兩個字串 s 和 t,它們只包含小寫字母。

字串 t 由字串 s 隨機重排,然後在隨機位置新增一個字母。

請找出在 t 中被新增的字母。

示例:

輸入:
s = "abcd"
t = "abcde"

輸出:
e

解釋:
'e' 是那個被新增的字母。

解法1。先構建好s中每個字元和其頻數的對應關係作為比較基準,再逐一遍歷t,找到沒有在s中出現過或者頻數對應不相等的字元並返回,程式碼如下。

執行用時: 28 ms, 在Find the Difference的Python提交中擊敗了97.36% 的使用者

class Solution(object):
    def findTheDifference(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: str
        """
        s_dict = {}
        for i in s:
            if i not in s_dict:
                s_dict[i] = 1
            else:
                s_dict[i] += 1
        
        for i in t:
            if i in s_dict and s_dict[i] == t.count(i):
                continue
            else:
                return i
        return -1

解法2。只用1層迴圈,遍歷26個字母,判斷在s和t中出現頻數是否一致,程式碼如下。

執行用時: 24 ms, 在Find the Difference的Python提交中擊敗了100.00% 的使用者

class Solution(object):
    def findTheDifference(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: str
        """
        alpha = "qwertyuiopasdfghjklzxcvbnm"
        for i in alpha:
            if s.count(i) != t.count(i):
                return i
        return 0

        # 其實上述還有優化版本,就是隻遍歷t,因為t是s的超集
        for i in set(t):
            if s.count(i) < t.count(i):
                return i
        return 0
            

解法3。思路非常之清奇,就是遍歷s,把t中和s一樣的元素統統刪掉,返回最後不一樣的那個元素,程式碼如下。

執行用時: 36 ms, 在Find the Difference的Python提交中擊敗了60.57% 的使用者 

class Solution(object):
    def findTheDifference(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: str
        """
        for i in s:
            t = t.replace(i,'',1)
        return t

結尾

解法1:原創

解法2&解法3:LeetCode