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"
相关推荐
颜酱3 小时前
图结构完全解析:从基础概念到遍历实现
javascript·后端·算法
m0_736919103 小时前
C++代码风格检查工具
开发语言·c++·算法
yugi9878384 小时前
基于MATLAB强化学习的单智能体与多智能体路径规划算法
算法·matlab
DuHz4 小时前
超宽带脉冲无线电(Ultra Wideband Impulse Radio, UWB)简介
论文阅读·算法·汽车·信息与通信·信号处理
Polaris北极星少女4 小时前
TRSV优化2
算法
代码游侠5 小时前
C语言核心概念复习——网络协议与TCP/IP
linux·运维·服务器·网络·算法
2301_763472465 小时前
C++20概念(Concepts)入门指南
开发语言·c++·算法
abluckyboy6 小时前
Java 实现求 n 的 n^n 次方的最后一位数字
java·python·算法
园小异6 小时前
2026年技术面试完全指南:从算法到系统设计的实战突破
算法·面试·职场和发展
m0_706653236 小时前
分布式系统安全通信
开发语言·c++·算法