I am trying to solve and understand the Build a String problem,
this piece of code pass 6 test cases and then failed, I got one failed test case but I am not able to understand why it is failed, could anyone explain why?
Test case
Input
a = 7890
b = 7891
s = acbcrsjcrscrsjcrcbcrsjcrscrsjccbcrsjcrscrsjcrcbcrsjrscrsjcrcbcrsjcrscrsjccbcrsjcrscrsjcrcbcsbcbcrsjh
Expected : 126246
Actually : 126247
static int buildString(int a, int b, String s) {
int result = 0;
String initial = "";
while (!s.equals("")) {
final String substring = s.substring(0, 1);
if (!initial.contains(substring)) {
initial += substring;
result += a;
s = s.substring(1);
} else {
String last = "";
for (int i = 1; i <= s.length(); i++) {
final String substring1 = s.substring(0, i);
if (initial.contains(substring1)) {
last = substring1;
} else {
break;
}
}
if (last.equals(substring) || b > (last.length() * a)) {
initial += substring;
result += a;
s = s.substring(1);
} else {
initial += last;
result += b;
s = s.substring(last.length());
}
}
}
return result;
}