本文共 2172 字,大约阅读时间需要 7 分钟。
You are playing the following Bulls and Cows game with your friend: You write down a number and ask your friend to guess what the number is. Each time your friend makes a guess, you provide a hint that indicates how many digits in said guess match your secret number exactly in both digit and position (called “bulls”) and how many digits match the secret number but locate in the wrong position (called “cows”). Your friend will use successive guesses and hints to eventually derive the secret number.
Write a function to return a hint according to the secret number and friend’s guess, use A to indicate the bulls and B to indicate the cows.
Please note that both secret number and friend’s guess may contain duplicate digits.
Example 1:
Input: secret = “1807”, guess = “7810”
Output: “1A3B” Explanation: 1 bull and 3 cows. The bull is 8, the cows are 0, 1 and 7.
Note: You may assume that the secret number and your friend’s guess only contain digits, and their lengths are always equal.
关键在于cow的情况下的多个相同元素问题。
用list存储非bull的元素,遇到相同元素cow计数并remove这个元素class Solution { public String getHint(String secret, String guess) { int bull = 0, cow = 0; ListlistSect = new ArrayList<>(); List listGues = new ArrayList<>(); for(int i = 0; i < secret.length(); i++){ if(secret.charAt(i) == guess.charAt(i)) bull++; else { listSect.add(secret.substring(i,i+1)); listGues.add(guess.substring(i,i+1)); } } for(int i = 0; i < listGues.size(); i++){ if(listSect.contains(listGues.get(i))){ cow++; listSect.remove(listGues.get(i)); } } String res = bull+"A"+cow+"B"; return res; }}
leetcode solution 1:
同一个数组用正数表示secret访问过,负数表示guess访问过。 cow只存在两种情况:secret先访问guess后访问 和 guess先访问secret后访问。如果是第一种情况,则数组为正数,即guess.charAt(i)-'0']-- > 0
public String getHint(String secret, String guess) { int bulls = 0; int cows = 0; int[] numbers = new int[10]; for (int i = 0; i0) cows++; } } return bulls + "A" + cows + "B";}
转载地址:http://wbqvb.baihongyu.com/