程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> JAVA綜合教程 >> Lettcode_299_Bulls and Cows

Lettcode_299_Bulls and Cows

編輯:JAVA綜合教程

Lettcode_299_Bulls and Cows


You are playing the followingBulls and Cowsgame 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:1bull and3cows. (The bull is8, the cows are0,1and7.)

 

Write a function to return a hint according to the secret number and friend's guess, useAto indicate the bulls andBto 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 1st1in friend's guess is a bull, the 2nd or 3rd1is 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)題意為給定兩串數字,其中的一串數字可以看作為密碼,另一串可看作為待猜測的數字,將猜對了的數字(位置和數字都相同)個數記為:個數+A,將位置不對而包含在密碼中的數字個數記為:個數+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";
	}
}</character,></character,>

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved