Skip to content

Instantly share code, notes, and snippets.

@ryancooper
Created October 1, 2014 08:27
Show Gist options
  • Save ryancooper/b4f6f892eb4769bfa41d to your computer and use it in GitHub Desktop.
Save ryancooper/b4f6f892eb4769bfa41d to your computer and use it in GitHub Desktop.
TopCoder SRM 144 DIV 1 300-points
class BinaryCode {
int charToNum(char c) {
return c - '0';
}
String solve(String message, char[] P, char first) {
boolean isValid = true;
int N = P.length;
P[0] = first;
P[1] = (char) ('0' + charToNum(message.charAt(0)) - charToNum(P[0]));
if (P[1] == '0' || P[1] == '1') {
for (int i = 1; i < N-1; ++i) {
P[i+1] = (char) ('0' + charToNum(message.charAt(i)) - charToNum(P[i]) - charToNum(P[i-1]));
if (P[i+1] != '0' && P[i+1] != '1') {
isValid = false;
break;
}
}
if (isValid)
return new String(P);
else
return "NONE";
}
else
return "NONE";
}
public String[] decode(String message) {
String[] res = new String[2];
int N = message.length();
if (N == 1) {
char c = message.charAt(0);
if (c != '0' && c != '1') {
res[0] = "NONE";
res[1] = "NONE";
}
else {
if (c == '0') {
res[0] = new String(message);
res[1] = "NONE";
}
else {
res[0] = "NONE";
res[1] = new String(message);
}
}
return res;
}
char P[] = new char[N];
res[0] = solve(message, P, '0');
res[1] = solve(message, P, '1');
return res;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment