直接用hashmap做的:
代码:
public class Solution { public String getHint(String secret, String guess) { if(secret == null || guess == null) return null; Map<Character, Integer> secretMap = new HashMap<>(); Map<Character, Integer> guessMap = new HashMap<>(); List<Character> list = new ArrayList<>(); int len = secret.length(); int numA = 0; int numB = 0; for(int i = 0; i < len; i++){ char c1 = secret.charAt(i); char c2 = guess.charAt(i); if(c1 == c2) numA++; else{ if(secretMap.containsKey(c1)) secretMap.put(c1, secretMap.get(c1)+1); else{ secretMap.put(c1, 1); list.add(c1); } if(guessMap.containsKey(c2)) guessMap.put(c2, guessMap.get(c2)+1); else guessMap.put(c2, 1); } } for(int i = 0; i < list.size(); i++){ char c = list.get(i); if(secretMap.containsKey(c) && guessMap.containsKey(c)) numB += Math.min(secretMap.get(c), guessMap.get(c)); } return numA+"A"+numB+"B"; } }
时间: 2024-11-05 15:56:33