Leetcode 299. Bulls and Cows

Problem

You are playing the Bulls and Cows game with your friend.

You write down a secret number and ask your friend to guess what the number is. When your friend makes a guess, you provide a hint with the following info:

  • The number of "bulls", which are digits in the guess that are in the correct position.
  • The number of "cows", which are digits in the guess that are in your secret number but are located in the wrong position. Specifically, the non-bull digits in the guess that could be rearranged such that they become bulls.

Given the secret number secret and your friend's guess guess, return the hint for your friend's guess.

The hint should be formatted as "xAyB", where x is the number of bulls and y is the number of cows. Note that both secret and guess may contain duplicate digits.

Algorithm

Use three list to record the state, if a number is used just ignore it.

Code

python3 复制代码
class Solution:
    def getHint(self, secret: str, guess: str) -> str:
        slen = len(secret)
        bulls = [0] * slen
        cows = [0] * slen
        used = [0] * slen
        for i in range(slen):
            if secret[i] == guess[i]:
                bulls[i] = 1
                used[i] = 1
        for i in range(slen):
            if not bulls[i]:
                for j in range(slen):
                    if i != j and not bulls[j] and not used[j]:
                        if secret[j] == guess[i]:
                            cows[i] = 1
                            used[j] = 1
                            break
        
        return str(sum(bulls)) + "A" + str(sum(cows)) + "B"
相关推荐
東隅已逝,桑榆非晚7 分钟前
AVL数实现
c++·笔记·学习·算法
驭渊的小故事34 分钟前
LeetCode 算法题解:滑动窗口与数组合并的实战应用
算法·leetcode·职场和发展
.YM.Z37 分钟前
优选算法——【双指针算法2】C++实现
开发语言·c++·算法
文丑颜不良啊1 小时前
LeetCode1501~1520题目解析
java·leetcode
zwc32104320552 小时前
第四周第五天——重构成类
c++·人工智能·opencv·算法·计算机视觉
Navigator_Z2 小时前
LeetCode //C - 1311. Get Watched Videos by Your Friends
c语言·算法·leetcode
云析赢指标公式网42 小时前
通达信ATAN均线角度公式源码笔记:四周期角度计算与DRAWBAND色带实现
笔记·算法
21岁被迫秃头2 小时前
SVT-AV1 Mini-Gop决策算法详解+源码分析.md
算法·av1·svt-av1·源码详解·mini-gop决策
Kobebryant-Manba2 小时前
IEKT向量矩阵流程&评估
人工智能·算法·矩阵
Js.Tx3 小时前
【具体数学 Concrete Mathematics】2.1.7 无限和式
算法·具体数学