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

LC - Bulls and Cows

时间:2015-11-04 07:05:48      阅读:230      评论:0      收藏:0      [点我收藏+]

标签:

 

https://leetcode.com/problems/bulls-and-cows/

Examples:

Secret: 1807                      Secret: 1123

Guess: 7810    ====> "0A3B"          Guess:  0111      ====> "1A1B"

Secret: 1122                      Secret: 121

Guess: 1222   ====> "3A0B"            Guess: 222        ====> "1A0B"

 

So getting the bull number is easy by just counting the number of matched pairs. The problem is to count the number of cows(mismatches).

1)Mismatched element from guess string has to be existed in secret string.

2)The # of mimatched occurence of that element in guess = # of mimatched occurence of that element in secret ;

3)We keep track of each mismatched pair by increasing the number by 1 for secret string and decreasing the number by 1 for guess string

4)If count[guess]>0,then that means  this element has occured in secret string and it was a mismactch, thus,we can increase the cow since this element is now found in the guess string;

5)If count[secret]<0,then that means  this element has occured in guess string and it was a mismactch, thus,we can increase the cow since this element is now found in the secret string;

    public String getHint(String secret, String guess) {
        if((secret==null||secret.length()==0)||(guess==null||guess.length()==0)){
            return "0A0B";
        }
        int match=0;
        int mismatch=0;
        int[] count=new int[10];
        for(int i=0;i<secret.length();i++){
             char s=secret.charAt(i);
             char g=guess.charAt(i);
        if(s==g){
            match++;
        }else{
             if(count[s-‘0‘]<0){
                mismatch++;
            }
            if(count[g-‘0‘]>0){
                mismatch++;
            }
            count[g-‘0‘]--;
            count[s-‘0‘]++;
        }
    }
    return match+"A"+mismatch+"B";
 }

 

LC - Bulls and Cows

标签:

原文地址:http://www.cnblogs.com/fifi043/p/4934917.html

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