码迷,mamicode.com
首页 > 其他好文 > 详细

[LC] 299. Bulls and Cows

时间:2020-02-12 22:25:22      阅读:81      评论:0      收藏:0      [点我收藏+]

标签:out   bsp   Plan   ++   string   san   col   hint   output   

Example 1:

Input: secret = "1807", guess = "7810"

Output: "1A3B"

Explanation: 1 bull and 3 cows. The bull is 8, the cows are 0, 1 and 7.

Example 2:

Input: secret = "1123", guess = "0111"

Output: "1A1B"

Explanation: The 1st 1 in friend‘s guess is a bull, the 2nd or 3rd 1 is a cow.
class Solution {
    public String getHint(String secret, String guess) {
        int[] nums = new int[10];
        int len = secret.length();
        int bulls = 0;
        int cows = 0;
        for (int i = 0; i < len; i++) {
            char sWord = secret.charAt(i);
            char gWord = guess.charAt(i);
            if (sWord == gWord) {
                bulls += 1;
            } else {
                if (nums[gWord - ‘0‘] > 0) {
                    cows += 1;
                }
                if (nums[sWord - ‘0‘] < 0) {
                    cows += 1;
                }
                nums[sWord - ‘0‘] += 1;
                nums[gWord - ‘0‘] -= 1;
            }
        }
        return bulls + "A" + cows + "B";
    }
}

 

[LC] 299. Bulls and Cows

标签:out   bsp   Plan   ++   string   san   col   hint   output   

原文地址:https://www.cnblogs.com/xuanlu/p/12301038.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!