首页 > 其他 > 详细

LC - Bulls and Cows

时间:2015-11-04 07:02:31      阅读:239      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!