公牛母牛问题

public class Solution {
    public String getHint(String secret, String guess) {
        int bulls = 0;
        int cows = 0;
        int[] nums = new int[10];
        int len = secret.length();
        for (int i = 0; i < len; i++) {
            if (secret.charAt(i) == guess.charAt(i)) {
                bulls++;
            } else {
                if (nums[secret.charAt(i) - '0']++ < 0)
                    cows++;
                if (nums[guess.charAt(i) - '0']-- > 0)
                    cows++;
            }
        }
        return bulls + "A" + cows + "B";
    }

    public static void main(String[] args) {
        String secret = "1807";
        String guess = "7810";
        System.out.println(new Solution().getHint(secret, guess));
    }
}

[leetcode原题] https://leetcode.com/problems/bulls-and-cows
[参考资料] https://leetcode.com/discuss/67031/one-pass-java-solution

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这个问题可以使用贪心算法来解决。我们可以从左到右遍历奶牛,记录当前连续的奶牛数量,以及公牛母牛的数量差。如果当前奶牛无法加入当前宿舍,那么我们就需要新开一个宿舍。 具体来说,我们可以记录当前宿舍内的公牛母牛数量以及宿舍内的总奶牛数量,以及当前连续的奶牛数量和公牛母牛数量差。如果当前奶牛可以加入当前宿舍,那么我们就将它加入宿舍,并更新宿舍内的数量信息;否则,我们就需要新开一个宿舍,并将当前奶牛加入新宿舍。 具体的实现细节可以参考下面的代码: ```python def minimum_shelters(n, m, cows): shelters = 0 current_gender = None current_count = 0 current_diff = 0 for cow in cows: if current_gender is None: # 第一个奶牛,初始化宿舍 current_gender = cow current_count = 1 elif current_gender == cow or abs(current_diff + (1 if cow == 'F' else -1)) <= m: # 可以加入当前宿舍 current_gender = current_gender or cow current_count += 1 current_diff += 1 if cow == 'F' else -1 else: # 需要新开一个宿舍 shelters += 1 current_gender = cow current_count = 1 current_diff = 0 return shelters + (1 if current_count > 0 else 0) ``` 其中,参数 `n` 表示奶牛的数量,参数 `m` 表示公牛母牛数量差的上限,参数 `cows` 是一个长度为 `n` 的字符串,表示每只奶牛的性别,其中 `'F'` 表示母牛,`'M'` 表示公牛。函数返回至少需要准备的宿舍数量。 例如,对于样例输入 `7 2 FMFMMFF`,函数的返回值为 `3`,表示最少需要准备 3 个宿舍。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值