299. Bulls and Cows

一、题目

  1、审题

  

  2、分析

    两个字符串数字中,位置相同且数字相同则 bull++;位置不同但数字相同则 cow++;统计 bull、cow 个数。

 

二、解答

  1、思路

    采用两个整形数组,num1[10], num2[10]; 

    遍历 secret、guess 相同位置的字符。

    若字符相同 则 bull ++ ;若字符不同,则将 secret 中改字符对应的数字作为下标在 num1 中 + 1, guess 字符在 num2中数值 +1。

    最终循环统计出 num1 与 num2 位置相同数值最小的所有元素的和,即为 cow 的个数。

    public String getHint2(String secret, String guess) {
        int bulls = 0, cows = 0;
        int[] numbers1 = new int[10];
        int[] numbers2 = new int[10];
        for (int i = 0; i < secret.length(); i++) {
            char ch1 = secret.charAt(i);
            char ch2 = guess.charAt(i);
            if(ch1 == ch2)
                bulls++;
            else {
                numbers1[ch1 - '0']++;
                numbers2[ch2 - '0']++;
            }
        }
        
        for (int i = 0; i < 10; i++) 
            cows += Math.min(numbers1[i], numbers2[i]);
        
        return bulls + "A" + cows + "B";
        
    }

 

  方法二、

    ①、采用一个额外数组:  numbers[10]

    ②、secret 与 guess 字符相同则 bull ++ ;

    ③、否则,secret 对应字符数字作为下标在 numbers 查找,若值 value < 0,则 cow++ ; value++;

      guess 对应数字在numbers 中的 value 如果 > 0, 则 cow++;value--。

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

 

    

 

posted @ 2018-11-26 15:38  skillking2  阅读(116)  评论(0编辑  收藏  举报