Skip to content

Instantly share code, notes, and snippets.

@wushbin
Last active February 16, 2020 01:59
Show Gist options
  • Save wushbin/1daf47bf0573d80fbf89feb8bc0dc6ee to your computer and use it in GitHub Desktop.
Save wushbin/1daf47bf0573d80fbf89feb8bc0dc6ee to your computer and use it in GitHub Desktop.
/**
Two pass solution
**/
class Solution {
public String getHint(String secret, String guess) {
if (secret == null || guess == null || secret.length() == 0 || guess.length() == 0) {
return "";
}
int len = secret.length();
int[] map = new int[10];
int A = 0;
int B = 0;
for (int i = 0; i < secret.length(); i++) {
map[secret.charAt(i) - '0'] += 1;
}
for (int i = 0; i < guess.length(); i++) {
char s = secret.charAt(i);
char c = guess.charAt(i);
if (map[c - '0'] > 0 && s == c) {
map[c - '0'] -= 1;
A += 1;
}
}
for (int i = 0; i < guess.length(); i++) {
char s = secret.charAt(i);
char c = guess.charAt(i);
if (s != c && map[c - '0'] > 0) {
map[c - '0'] -= 1;
B += 1;
}
}
return A + "A" + B + "B";
}
}
/**
One pass solution
**/
class Solution {
public String getHint(String secret, String guess) {
if (secret == null || guess == null || secret.length() == 0 || guess.length() == 0) {
return "";
}
int[] map = new int[10];
int A = 0;
int B = 0;
for (int i = 0; i < guess.length(); i++) {
char s = secret.charAt(i);
char c = guess.charAt(i);
if (s == c) {
A += 1;
} else {
if (map[s - '0'] < 0) {
B += 1;
}
if (map[c - '0'] > 0) {
B += 1;
}
map[s - '0'] += 1;
map[c - '0'] -= 1;
}
}
return A + "A" + B + "B";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment