Palantir Technology Interview Question
Software EngineersCountry: United States
Interview Type: Phone Interview
package com.home.careercup;
public class DecodeCFNString {
public static void main(String[] args) throws Exception {
String in = "9_r4_brbrbr_3b2rb_b2r2br_r2b3rb";
char[][] result = decode(in);
for (char[] s : result) {
System.out.println(s);
}
}
static char[][] decode(String cfn) throws Exception {
char[][] result = new char[6][7];
char[] code = cfn.toCharArray();
StringBuilder sb = new StringBuilder();
int expand = 0;
for (char c : code) {
if (expand > 0) {
for (; expand > 0; expand--)
sb.append(c);
continue;
}
switch (c) {
case 'r':
sb.append(c);
break;
case 'b':
sb.append(c);
break;
case '_':
sb.append(c);
break;
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '0':
expand = (int) c - '0';
break;
default:
throw new Exception("invalid cfn string, found char " + c);
}
}
// now we need to end up with a 7*6 length char string
if (sb.toString().length() != 7 * 6) throw new Exception("invalid cf string");
final String rs = sb.toString();
for (int i = 0, start = 0, end = 7; end <= 42; i++, start = end, end += 7) {
result[i] = rs.substring(start, end).toCharArray();
}
for (char[] s : result) {
validate(s);
}
return result;
}
private static void validate(char[] s) {
//TODO:
//throw exception if the validation does NOT succeed
// for example there may be a digit that is placed
// such that the number of spaces to its right does
// not justify its value
return;
}
}
- mirak94 June 19, 2018