Leetcode_299_Bulls and Cows
本文是在學習中的總結,歡迎轉載但請註明出處:http://blog.csdn.net/pistolove/article/details/50768550
You are playing the following Bulls and Cows game with your friend: You write down a number and ask your friend to guess what the number is. Each time your friend makes a guess, you provide a hint that indicates how many digits in said guess match your secret number exactly in both digit and position (called "bulls") and how many digits match the secret number but locate in the wrong position (called "cows"). Your friend will use successive guesses and hints to eventually derive the secret number.
For example:
Secret number: "1807" Friend‘s guess: "7810"Hint:
1
bull and 3
cows. (The bull is 8
, the cows are 0
, 1
and 7
.)Write a function to return a hint according to the secret number and friend‘s guess, use A
to indicate the bulls and B
to indicate the cows. In the above example, your function should return "1A3B"
Please note that both secret number and friend‘s guess may contain duplicate digits, for example:
Secret number: "1123" Friend‘s guess: "0111"In this case, the 1st
1
in friend‘s guess is a bull, the 2nd or 3rd 1
is a cow, and your function should return "1A1B"
.You may assume that the secret number and your friend‘s guess only contain digits, and their lengths are always equal
思路:
(1)題意為給定兩串數字,當中的一串數字能夠看作為password,還有一串可看作為待推測的數字,將猜對了的數字(位置和數字都同樣)個數記為:個數+A,將位置不正確而包括在password中的數字個數記為:個數+B。
(2)該題主要考察字符匹配問題。因為兩串數字中數的個數同樣,所以,對於位置同樣且數字亦同樣的情況。僅僅需遍歷一次就能得到bull的個數;而對於位置不同且含有同樣數的情況,則須要進行特殊處理以得到cow的個數。
一方面。可能某一個數在當中的某一串數中出現了多次。還有一方面,位置同樣且數同樣的情況也須要進行過濾。此處,創建一個Map來進行存儲和過濾。當中。map的key為數串中的數,value為該數出現的次數。這樣通過一次遍歷就可以將數和其個數存儲起來。然後再進行兩次遍歷,分別得到同一位置上數同樣情況的個數和不同位置上數同樣情況的個數,即為所求。
詳情見下方代碼。
(3)希望本文對你有所幫助。
謝謝。
算法代碼實現例如以下:
import java.util.HashMap; import java.util.Map; public class Bulls_and_Cows { public static void main(String[] args) { System.err.println(getHint("1122", "1222")); } public static String getHint(String secret, String guess) { char[] se = secret.toCharArray(); char[] gu = guess.toCharArray(); int len = se.length; int bull = 0; int cow = 0; Map<Character, Integer> seHas = new HashMap<Character, Integer>(); for (int i = 0; i < len; i++) { if (!seHas.containsKey(se[i])) { seHas.put(se[i], 1); } else { seHas.put(se[i], seHas.get(se[i]) + 1); } } Boolean[] b = new Boolean[len]; for (int i = 0; i < len; i++) { if (se[i] == gu[i]) { b[i] = true; seHas.put(gu[i], seHas.get(gu[i])-1); cow++; }else { b[i] = false; } } for (int j = 0; j < len; j++) { if(b[j] == false && seHas.get(gu[j])!=null && seHas.get(gu[j])>0) { bull ++; seHas.put(gu[j], seHas.get(gu[j])-1); } } return cow + "A" + bull + "B"; } }
Leetcode_299_Bulls and Cows