1. 题意:
给出两条integer string 分别为 secret 和 guess。让判断答题者分别猜对和猜错了几个数字。
猜对:定义为bulls(A),必须一样且在secret和guess里分别对应的index一样。
猜错:cows(B), 必须一样,但在secret和guess里分别对应的index不同。
2. 解题:
关键词:hashmap
1)走一遍secret, 首先建立map, key: s 里的char,value:s里char的频率。
2) 走一遍guess,如果对应char和s里的char一样,bulls += 1,频率 -= 1. 如果不一样时切记要检查来自guess的那个char是否有存在再map里头,如果存在,才能把 cow += 1,然后再把对应value -=1.
3)最后还要再过一遍map,把多余的cows减去。。
3. 代码:
class Solution { public String getHint(String secret, String guess) { String result = ""; Map<Character, Integer> charStoFreq = new HashMap<>(); int bulls = 0, cows = 0; int secLen = secret.length(); for (int i = 0; i < secLen; i++) { char fromSec = secret.charAt(i); if(! charStoFreq.containsKey(fromSec)) { charStoFreq.put(fromSec, 1); } else { charStoFreq.put(fromSec, charStoFreq.get(fromSec) + 1); } } for (int i = 0; i < secLen; i++) { char FromGuess = guess.charAt(i); char FromSecret = secret.charAt(i); if (FromGuess == FromSecret) { bulls += 1; charStoFreq.put(FromSecret, charStoFreq.get(FromSecret) - 1); } else { if (charStoFreq.containsKey(FromGuess)) { cows += 1; charStoFreq.put(FromGuess, charStoFreq.get(FromGuess) - 1); } } } for (Map.Entry<Character, Integer> entry : charStoFreq.entrySet()) { int value = entry.getValue(); if (value < 0) { cows = cows + value; } } return String.valueOf(bulls) + "A" + String.valueOf(cows) +"B"; } }