299. Bulls and Cows
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.
For example:
Secret number: "1807"
Friend's guess: "7810"
Hint: 1 bull and 3 cows. (The bull is 8, the cows are 0, 1 and 7.)
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. In the above example, your function should return “1A3B”.
Please note that both secret number and friend’s guess may contain duplicate digits, for example:
Secret number: "1123"
Friend's guess: "0111"
In this case, the 1st 1 in friend’s guess is a bull, the 2nd or 3rd 1 is a cow, and your function should return “1A1B”.
You may assume that the secret number and your friend’s guess only contain digits, and their lengths are always equal.
一个定义新运算的问题,本质上是对两个字符串的比较,如果串secret中的元素与guess中的元素等值同位,则’Bull’的值+1;如果串guess中的元素在串guess中出现过,则’Cow’的值+1.
这个问题可以用两个哈希表来解决,两个哈希表中分别存储两个串中每个元素的出现次数即可,不过这里我们并不需要进行频繁的查找操作,只是需要一个映射而已,所以我们大可不必用一个哈希表来解决问题,所以下面介绍一个编程技巧:
核心思想是用一个数组充当哈希表起到的计数作用,具体实现如下:
Using array as a simple counter
A simple array could be used as a counter. An array could be used to keep track of the frequency of each character. For example, if the input consists of ASCII characters, we could just use an integer array of size 256 to keep track of the frequency.
For example, the following program calculates each character’s frequency using a simple array of size 256.
private static void printFreq(char[] str) {
int[] freq = new int[256];
for (int i = 0; i < str.length; i++) {
freq[str[i]]++;
}
for (int i = 0; i < 256; i++) {
if (freq[i] > 0) {
System.out.println("[" + (char)(i) + "] = " + freq[i]);
}
}
}
public static void main(String[] args) {
char[] str = "Hello world".toCharArray();
printFreq(str);
}
Output:
[ ] = 1
[H] = 1
[d] = 1
[e] = 1
[l] = 3
[o] = 2
[r] = 1
[w] = 1
Why do we choose size 256? Why not 128 or 26? The reason is because there are a total of 256 possible ASCII characters, from 0 to 255. If you are sure that the input characters are all lowercase letters (a - z), then you can save some space by using an array of size 26:
private static void printFreq(char[] str) {
int[] freq = new int[26];
for (int i = 0; i < str.length; i++) {
// 'a' has an ascii value of 97, so there is an offset in accessing the index.
freq[str[i] - 'a']++;
}
for (int i = 0; i < 26; i++) {
if (freq[i] > 0) {
System.out.println("[" + (char)(i + 'a') + "] = " + freq[i]);
}
}
}
public static void main(String[] args) {
char[] str = "helloworld".toCharArray();
printFreq(str);
}
Output:
[d] = 1
[e] = 1
[h] = 1
[l] = 3
[o] = 2
[r] = 1
[w] = 1
Using a hash table
Now, what if the input contains unicode characters? In Java, each character is represented internally as 2 bytes, or 16 bits. That means you can increase the array size to 2^{16} = 65536 2^16=65536, which would work but seems like a waste of space. For example, what if your input has only 10 characters? Most of the array elements will be initialized to 0 and to print the frequencies we need to traverse all 65536 elements one by one, which is inefficient.
A better method is to use a hash table, in Java it’s called HashMap, in C++ it’s called unordered_map, and in Python it’s called dict.
private static void printFreq(char[] str) {
Map<Character, Integer> freq = new HashMap<>();
for (int i = 0; i < str.length; i++) {
if (freq.containsKey(str[i])) {
freq.put(str[i], freq.get(str[i]) + 1);
} else {
freq.put(str[i], 1);
}
}
for (Map.Entry<Character, Integer> entry : freq.entrySet()) {
System.out.println("[" + (char)(entry.getKey()) + "] = " + entry.getValue());
}
}
public static void main(String[] args) {
char[] str = "◣⚽◢⚡◣⚾⚡◢".toCharArray();
printFreq(str);
}
Output:
[⚡] = 2
[◢] = 2
[◣] = 2
[⚽] = 1
[⚾] = 1
引用自Leetcode course部分,原文写的很好,在此就不再造轮子了。
对于这道题,思路是:如果两个字符串相比较,对应位置上的元素相等,则bull+1,否则,统计不成对元素出现次数,代码如下:
class Solution {
public:
string getHint(string secret, string guess) {
if(secret.empty()||guess.empty())
return "0A0B";
vector<int> countS(10,0);
vector<int> countG(10,0);
string res;
int countA=0,countB=0;
for(int i=0;i<secret.size();i++){
if(secret[i]==guess[i])
countA++;
else{
/*统计不成对元素个数*/
countS[secret[i]-'0']++;
countG[guess[i]-'0']++;
}
}
for(int i=0;i<countS.size();i++)
countB+=min(countS[i],countG[i]);
res=to_string(countA)+'A'+to_string(countB)+'B';
return res;
}
};