題目描述如下:
分析如下:
a.建立兩個字典,存放solution和guess顏色出現的個數
b.因爲題目中說“猜中”不能算入“僞猜中”,因此“猜中”的優先級更高
c.先計算猜中的次數,對應的字典-1
d.再計算僞猜中的次數,對應的字典-1
e.最後返回結果即可
代碼如下:
1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 """ 4 # @Time : 2020/7/15 9:14 5 6 # @Author : ZFJ 7 8 # @File : 珠璣妙算.py 9 10 # @Software: PyCharm 11 """ 12 13 from collections import Counter 14 15 16 class Solution(object): 17 def masterMind(self, solution, guess): 18 """ 19 對於這種涉及到次數的問題,我的通用解法均是使用字典計數 20 首先我們建立兩個字典進行計數 21 接着先計算猜中的,在計算僞猜中的,然後將對應位置的計數減一即可 22 :type solution: str 23 :type guess: str 24 :rtype: List[int] 25 """ 26 # 使用字典記錄下每個字符串中字幕出現的次數 27 dict_solution = Counter(solution) 28 dict_guess = Counter(guess) 29 # 答案列表 30 result = [0, 0] 31 # 找到真的猜中的次數 32 for i in range(len(solution)): 33 # 對應位置的值相等 34 if solution[i] == guess[i]: 35 # 結果中的真猜中次數加1 36 result[0] += 1 37 # 對應的字典計數減一 38 dict_solution[solution[i]] -= 1 39 dict_guess[guess[i]] -= 1 40 # 找到僞猜中次數 41 for j in range(len(solution)): 42 # 根據條件,判斷條件是猜測的字母在原來的字符串中,並且二者的計數均不能爲0 43 if guess[j] in solution and dict_solution[guess[j]] > 0 and dict_guess[guess[j]] > 0: 44 result[1] += 1 45 dict_solution[guess[j]] -= 1 46 dict_guess[guess[j]] -= 1 47 48 return result 49 50 51 if __name__ == "__main__": 52 test = Solution().masterMind(solution="RGRB", guess="BBBY") 53 print(f"猜中 {test[0]}次,僞猜中{test[1]}次。")
運行消耗如下: