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.

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;
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;
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

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;
}
};

学籍管理系统文档

北邮教务系统评教脚本

Published on September 17, 2017

72.Edit distance

Published on September 17, 2017