Leetcode 299. Bulls and Cows

来源:互联网 发布:数据出版相关论文 编辑:程序博客网 时间:2024/06/05 20:16
public class Solution {    public String getHint(String secret, String guess) {        int bull = 0, cow = 0;        int[] cnt_se = new int[10];        int[] cnt_gu = new int[10];                // count bulls first        // count cows using two arrays to save the count for each number appeared in secret and guess        // e.g. cnt_secret[0] saves the number of 0s appeared in secret        for (int i=0; i<secret.length(); i++) {            if (secret.charAt(i) == guess.charAt(i))                bull++;            else {                cnt_se[secret.charAt(i)-'0']++;                cnt_gu[guess.charAt(i)-'0']++;            }        }                // chosse minimum count if a number appears in both secret and guess        // b/c multiple cows count only once        for (int j=0; j<10; j++)            cow += Math.min(cnt_se[j], cnt_gu[j]);                    return bull + "A" + cow + "B";    }}

0 0