标签:ret math list record [] class turn 简化 length
1 //自己简化了 100% 2 class Solution { 3 public String getHint(String secret, String guess) { 4 int bull = 0; 5 int cow = 0; 6 char[] arr1 = secret.toCharArray(); 7 char[] arr2 = guess.toCharArray(); 8 for(int i = 0; i < secret.length(); i++){ 9 if(arr1[i] == arr2[i]){ 10 bull++; 11 arr1[i] = ‘a‘; 12 arr2[i] = ‘a‘; 13 } 14 } 15 int[] record1 = new int[10]; 16 int[] record2 = new int[10]; 17 for(int i = 0; i < arr1.length; i++){ 18 if(arr1[i] != ‘a‘){ 19 record1[arr1[i] - ‘0‘]++; 20 } 21 if(arr2[i] != ‘a‘){ 22 record2[arr2[i] - ‘0‘]++; 23 } 24 } 25 for(int i = 0; i < 10; i++){ 26 cow += Math.min(record1[i], record2[i]); 27 } 28 String res = "" + bull + "A" + cow + "B"; 29 return res; 30 31 } 32 } 33 34 35 36 //Old 37 class Solution { 38 public String getHint(String secret, String guess) { 39 HashMap<Character, List<Integer>> map1 = new HashMap<>(); 40 HashMap<Character, List<Integer>> map2 = new HashMap<>(); 41 char[] arr1 = secret.toCharArray(); 42 char[] arr2 = guess .toCharArray(); 43 for(int i = 0; i < arr1.length; i++){ 44 if(map1.containsKey(arr1[i])){ 45 map1.get(arr1[i]).add(i); 46 }else{ 47 List<Integer> list = new ArrayList<>(); 48 list.add(i); 49 map1.put(arr1[i], list); 50 } 51 } 52 53 for(int i = 0; i < arr2.length; i++){ 54 if(map2.containsKey(arr2[i])){ 55 map2.get(arr2[i]).add(i); 56 }else{ 57 List<Integer> list = new ArrayList<>(); 58 list.add(i); 59 map2.put(arr2[i], list); 60 } 61 } 62 int bull = 0, cow = 0; 63 for(char c : map2.keySet()){ 64 if(!map1.containsKey(c)){ 65 continue; 66 }else{ 67 int size1 = map2.get(c).size(); 68 int size2 = map1.get(c).size(); 69 for(int pos : map2.get(c)){ 70 for(int i = 0; i < map1.get(c).size(); i++){ 71 if(pos == map1.get(c).get(i)){ 72 bull++; 73 size1--; 74 size2--; 75 } 76 } 77 } 78 cow += Math.min(size1, size2); 79 } 80 } 81 String res = "" + bull + "A" + cow + "B"; 82 return res; 83 84 } 85 }
标签:ret math list record [] class turn 简化 length
原文地址:https://www.cnblogs.com/goPanama/p/9802085.html