【leetcode】299.(Medium)Bulls and Cows

    xiaoxiao2025-06-20  28

    思路

    bulls很好算,过一遍两个数组找对应的即可

    cows的话,首先如果一个坐标的数字已经算作bull的话就不能再算作cow,用isBull[]数组将所有的bull坐标记录下来,算cow的时候就不用管这些坐标的数字。 然后记录一下cows的数字都有哪些,每个数字都出现了多少次,用mapSecret保存下来。然后再算一下guess中的数字。

    提交代码:

    class Solution { public String getHint(String secret, String guess) { int bulls=0,cows=0,len=secret.length(); Map<Character,Integer> mapSecret=new HashMap<>(); Map<Character,Integer> mapGuess=new HashMap<>(); boolean[] isBull=new boolean[len]; char c1,c2; for(int i=0;i<len;i++) { c1=secret.charAt(i); c2=guess.charAt(i); if(c1==c2) { bulls++; isBull[i]=true; }else { if(!mapSecret.containsKey(c1)) mapSecret.put(c1, 1); else mapSecret.put(c1,mapSecret.get(c1)+1); } } for(int i=0;i<len;i++) { if(!isBull[i]) { c2=guess.charAt(i); if(mapSecret.containsKey(c2)) { if(mapGuess.containsKey(c2)) mapGuess.put(c2,Math.min(mapSecret.get(c2), mapGuess.get(c2)+1)); else mapGuess.put(c2,1); } } } for(Integer value : mapGuess.values()) cows+=value; return Integer.toString(bulls)+"A"+Integer.toString(cows)+"B"; } }

    运行结果

    最新回复(0)