Lc-bulls and cows

Source: Internet
Author: User

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 was 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 have to is existed in secret string.

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

3) We keep track's 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 have occured in secret string and it is a mismactch, Thus,we can incr Ease the cow since this element was now found in the Guess string;

5) If count[secret]<0,then That means this element have occured in guess string and it is a mismactch, Thus,we can incr Ease the cow since this element was now found in the secret string;

     Publicstring Gethint (String secret, String guess) {if((secret==NULL|| Secret.length () ==0) | | (guess==NULL|| Guess.length () ==0)){            return"0A0B"; }        intMatch=0; intMismatch=0; int[] count=New int[10];  for(intI=0;i<secret.length (); i++){             Chars=Secret.charat (i); Charg=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 ']++; }    }    returnmatch+ "A" +mismatch+ "B"; }

Lc-bulls and cows

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.