代码
import java.util.*;
class Solution {
public String getHint(String secret, String guess) {
int count1=0;
int count2=0;
int[] nums=new int[10];//0----9
for(int i=0;i<guess.length();i++)
{
int s1 = secret.charAt(i)-'0';
int s2 = guess.charAt(i)-'0';
if(s1==s2) count1++;
else{//不相等的情况
if(nums[s1]<0){//之前在guess中出现过
count2++;
}
if(nums[s2]>0){//之前在secret中出现过
count2++;
}
nums[s1]++;//s中
nums[s2]--;//g中
}
}
return count1+"A"+count2+"B";
}
public String getHint2(String secret, String guess) {
int count1=0;
int count2=0;
HashMap<Character,Integer> smap=new HashMap<>();
HashMap<Character,Integer> gmap=new HashMap<>();
for(int i=0;i<secret.length();i++)
{
char s1 = secret.charAt(i);
char s2 = guess.charAt(i);
smap.put(s1, smap.getOrDefault(s1,0)+1);
gmap.put(s2, gmap.getOrDefault(s2,0)+1);
if(s1==s2)
{
count1++;
}
}
for(Character c: gmap.keySet())
{
int temp1=smap.getOrDefault(c,0);
int temp2=gmap.getOrDefault(c,0);
count2+=Math.min(temp1,temp2);
}
return count1+"A"+(count2-count1)+"B";
}
}