zoukankan      html  css  js  c++  java
  • Leetcode刷题日记-程序员面试经典(2020.7.15):珠玑妙算

    题目描述如下:

     分析如下:

    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]}次。")

    运行消耗如下:

  • 相关阅读:
    [LeetCode]Subsets II
    [LeetCode]Subsets
    [LeetCode]Combinations
    [LeetCode]Minimum Window Substring
    [LeetCode]Search a 2D Matrix
    [LeetCode]Edit Distance
    [LeetCode]Simplify Path
    Adaboost算法
    [LeetCode]Text Justification
    31、剑指offer--从1到n整数中1出现次数
  • 原文地址:https://www.cnblogs.com/ZFJ1094038955/p/13303918.html
Copyright © 2011-2022 走看看