您的位置:首页 > 其它

78.Bulls and Cows

2016-01-24 16:00 253 查看
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.

分析:猜数字的游戏,返回对方猜出的数字有几个在正确位置,有几个数字正确但是没有在正确的位置。分别用两个链表存secret和guess中的字符。

依次读secret和guess中的字符,若sc=gc,则不加入这两个链表,如果不相等,则分别加入到其对应链表的后面。

最后计算看list1和list2中相同元素的个数,即为数字正确但是位置不对的元素个数。每当发现一个数字正确但是位置不对的数字则把list1中这个元素删除,避免出现重复计算。

/**
* 猜数字的游戏,返回对方猜出的数字有几个在正确位置,有几个数字正确但是没有在正确的位置。
* 用hash表存<sc,gc>。依次读secret和guess中的字符,若sc=gc,则不入hash表,直接把正确数字的个数加1.
* 如果sc和gc不相等,则入hash表,最后看keyset和valueset中相同元素的个数,即为数字正确但是位置不对的元素个数。
* 题目中有说明假设输入的两个字符串的长度相等,而且全部是数字。 You may assume that the secret number and
* your friend's guess only contain digits, and their lengths are always equal.
*
* 实现的时候发现hash表的问题是当多个sc相同的时候会出问题。所以,换成分别用两个链表。
* 这个才是正确的答案~~~~~
*/
public String getHint2(String secret, String guess) {
int bullsNum = 0;// 完全正确数字的个数
int cowsNum = 0;// 数字正确但是位置不对的个数
ArrayList<Character> list1 = new ArrayList<Character>();
ArrayList<Character> list2 = new ArrayList<Character>();
int len = secret.length();
/* 构造hash表的同时计算完全正确数字的个数 */
for (int i = 0; i < len; i++) {
char sc = secret.charAt(i);
char gc = guess.charAt(i);
if (sc == gc) {
bullsNum++;
} else {
list1.add(sc);
list2.add(gc);
}
}
/* 计算看list1和list2中相同元素的个数,即为数字正确但是位置不对的元素个数 */
int size = list1.size();
for(int i=0;i<size;i++){
Character c = list2.get(i);
if(list1.contains(c)){/*记得在list1中把这个元素给删除了,因为"1123"和"0111"这种是只有一个数字是属于正确但是位置不对*/
cowsNum++;
list1.remove(c);
}
}

return bullsNum + "A" + cowsNum + "B";
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: