1、题目数组
一、审题spa
二、分析3d
两个字符串数字中,位置相同且数字相同则 bull++;位置不一样但数字相同则 cow++;统计 bull、cow 个数。code
2、解答blog
一、思路字符串
采用两个整形数组,num1[10], num2[10]; get
遍历 secret、guess 相同位置的字符。class
若字符相同 则 bull ++ ;若字符不一样,则将 secret 中改字符对应的数字做为下标在 num1 中 + 1, guess 字符在 num2中数值 +1。循环
最终循环统计出 num1 与 num2 位置相同数值最小的全部元素的和,即为 cow 的个数。遍历
public String getHint2(String secret, String guess) { int bulls = 0, cows = 0; int[] numbers1 = new int[10]; int[] numbers2 = new int[10]; for (int i = 0; i < secret.length(); i++) { char ch1 = secret.charAt(i); char ch2 = guess.charAt(i); if(ch1 == ch2) bulls++; else { numbers1[ch1 - '0']++; numbers2[ch2 - '0']++; } } for (int i = 0; i < 10; i++) cows += Math.min(numbers1[i], numbers2[i]); return bulls + "A" + cows + "B"; }
方法2、
①、采用一个额外数组: numbers[10]
②、secret 与 guess 字符相同则 bull ++ ;
③、不然,secret 对应字符数字做为下标在 numbers 查找,若值 value < 0,则 cow++ ; value++;
guess 对应数字在numbers 中的 value 若是 > 0, 则 cow++;value--。
public String getHint(String secret, String guess) { int bulls = 0, cows = 0; int[] numbers = new int[10]; for (int i = 0; i < secret.length(); i++) { char ch1 = secret.charAt(i); char ch2 = guess.charAt(i); if(ch1 == ch2) bulls++; else { if(numbers[ch1 - '0']++ < 0) cows++; if(numbers[ch2 - '0']-- > 0) cows++; } } return bulls + "A" + cows + "B"; }