public String getHint(String secret, String guess) { /* 判断bull 是通过比较两个字符串的每一位,每次相同就删除该字符出现的次数,因为后边的 要判断cow不能占用这些 判断cow只要检测出去被占用的还有没有该字符 */ //key记录字符,value记录出现的次数 Map<Character,Integer> map = new HashMap<>(); String res = ""; int a = 0; int b = 0; boolean[] boo = new boolean[secret.length()]; for (int i = 0; i < secret.length(); i++) { char cur = secret.charAt(i); int num = map.getOrDefault(cur,0); num++; map.put(cur,num); } //判断bull和cow不能一起,要先判断bull,因为如果在判断cow的过程中会占用,会影响bull for (int i = 0; i < guess.length(); i++) { char cur = guess.charAt(i); if (cur==secret.charAt(i)) { a++; boo[i] = true; map.put(cur,map.get(cur)-1); } } for (int i = 0; i < guess.length(); i++) { char cur = guess.charAt(i); if (!boo[i]&&map.containsKey(cur)&&map.get(cur)>0) { b++; map.put(cur,map.get(cur)-1); } } res = a+"A"+b+"B"; return res;}
原文地址:https://www.cnblogs.com/stAr-1/p/8323704.html
时间: 2024-12-17 09:49:05