morbidCode - 5 months ago 31
Java Question

# PrefixAgain solution in codingbat

I'm currently doing codingbat problems for fun, and I just done this problem.

"Given a string, consider the prefix string made of the first N chars of the string. Does that prefix string appear somewhere else in the string? Assume
that the string is not empty and that N is in the range 1..str.length(). prefixAgain("abXYabc", 1) → true prefixAgain("abXYabc", 2) → true prefixAgain("abXYabc",
3) → false"
http://codingbat.com/prob/p136417

And my solution is:

``````public boolean prefixAgain(String str, int n) {
return (str.replaceFirst(Character.toString(str.charAt(n-1)),"").contains(Character.toString(str.charAt(n-1))));
}
``````

Now, I didn't really understand the problem while writing this code and I thought only to find the occurance of the character of the specified index and
ignore the characters before it using the .contains() method. So I'm really not finding the prefix as the problem instructed. I just found my mistake after submitting it. However, this solution passed the exercise.
When I test it with my own input, such as

``````prefixAgain("abcccccbx", 2);
``````

it returned true instead of false. So am I missing some reason why codingbat accepted my solution even though it's totally wrong?

Restate your strategy (algorithm): Do the first N characters in a string appear anywhere else in the string? Simplest solution would be to look for that string in the 2nd through last characters of the original string. Like below (even if someone gives you an assumption, always check!)

``````public boolean prefixAgain(String str, int n) {
boolean result = false;
if (n < str.length() &&
(str.substring(1)).indexOf(str.substring(0,n)) > -1
) {
result = true;
}
return result;
}
``````
Source (Stackoverflow)