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"
相关推荐
courniche32 分钟前
ECDH、ECDHE、ECDLP、ECDSA傻傻分不清?
算法·密码学
前端小刘哥43 分钟前
超低延迟与高并发:视频直播点播平台EasyDSS在游戏直播场景的技术实践
算法
毅炼1 小时前
常见排序算法
java·算法·排序算法
猫梦www1 小时前
力扣21:合并两个有序链表
数据结构·算法·leetcode·链表·golang·力扣
Han.miracle1 小时前
数据结构——排序的学习(一)
java·数据结构·学习·算法·排序算法
爱coding的橙子1 小时前
每日算法刷题Day76:10.19:leetcode 二叉树12道题,用时3h
算法·leetcode·职场和发展
liu****3 小时前
20.哈希
开发语言·数据结构·c++·算法·哈希算法
夏鹏今天学习了吗3 小时前
【LeetCode热题100(47/100)】路径总和 III
算法·leetcode·职场和发展
smj2302_796826523 小时前
解决leetcode第3721题最长平衡子数组II
python·算法·leetcode
m0_626535204 小时前
力扣题目练习 换水问题
python·算法·leetcode