原题链接在这里:https://leetcode.com/problems/bulls-and-cows/
猜字游戏,用HashMap 来记录character 和出现的次数。若是secret.charAt(i) != guess.charAt(i)时,secret扫过数字,mark对应位置加一,guess扫过数字,mark对应位置减一。 若是mark[secret.charAt(i) - ‘0‘] 小于0, 说明guess 已经更新过这个位置,此时numCow++. 反过来若是 mark[guess.charAt(i) - ‘0‘] 大于0, 说明secret 已经跟新过这个位置, 此时numCow++.
只需要扫一遍两个string, Time O(n), n是string长度的二倍。用了一个长度为10的array当HashMap使用,SpaceO(1).
AC Java:
1 public class Solution { 2 public String getHint(String secret, String guess) { 3 int numBull = 0; 4 int numCow = 0; 5 int [] mark = new int[10]; 6 for(int i = 0; i<secret.length(); i++){ 7 if(secret.charAt(i) == guess.charAt(i)){ 8 numBull++; 9 }else{ 10 if(mark[secret.charAt(i) - ‘0‘]++ < 0){ 11 numCow++; 12 } 13 if(mark[guess.charAt(i) - ‘0‘]-- > 0){ 14 numCow++; 15 } 16 } 17 } 18 String res = String.valueOf(numBull) + "A" + String.valueOf(numCow) + "B"; 19 return res; 20 } 21 }
原文:http://www.cnblogs.com/Dylan-Java-NYC/p/4929636.html