leetcode 299:Bulls and Cows

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

You are playing the following Bulls and Cows game with your friend: You write a 4-digit secret number and ask your friend to guess it, each time your friend guesses a number, you give a hint, the hint tells your friend how many digits are in the correct positions (called "bulls") and how many digits are in the wrong positions (called "cows"), your friend will use those hints to find out the secret number.

For example:

Secret number:  1807
Friend's guess: 7810
Hint:  1  bull and  3  cows. (The bull is  8 , the cows ar01 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.

You may assume that the secret number and your friend's guess only contain digits, and their lengths are always equal.

/* 思路:统计两个字符串中位置相同且数字相同和位置不同而数字相同的数目。
 *             两次遍历。1.统计位置相同且数字相同个数。且将位置不同的字母都保存。
 *                                 2.统计含有相同数字的个数。
*/


public class Solution{
	public String getHint(String secret, String guess) {
	    int countA = 0, countB = 0;
	    
	    LinkedList<Character> cur = new LinkedList<Character>();
	    LinkedList<Integer> index = new LinkedList<Integer>();
	    
	    for(int i = 0; i < secret.length(); i++) {
	        if(secret.charAt(i) == guess.charAt(i)) {
	            countA++;
	        } else {
	        	index.offer(i);
	        	cur.add(secret.charAt(i));
	        }
	    }
	    
	    while(!index.isEmpty()) {
	    	char ch = guess.charAt(index.poll()); 
	    	if(cur.contains(ch)) {
	    		countB++;
	    		//ch需要转换为Character
	    		cur.remove(Character.valueOf(ch));
	    	} 
	    }
	    
	    return Integer.toString(countA)  + "A" + Integer.toString(countB)  + "B";
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值