string – Java codingbat help – withoutString
Your solution IS failing AND there is a display bug in coding bat.
The correct output should be:
withoutString(This is a FISH, IS) -> Th a FH
Yours is:
withoutString(This is a FISH, IS) -> Th a FH
Yours fails because it is removing spaces, but also, coding bat does not display the correct expected and run output string due to HTML removing extra spaces.
This recursive solution passes all tests:
public String withoutString(String base, String remove) {
int remIdx = base.toLowerCase().indexOf(remove.toLowerCase());
if (remIdx == -1)
return base;
return base.substring(0, remIdx ) +
withoutString(base.substring(remIdx + remove.length()) , remove);
}
Here is an example of an optimal iterative solution. It has more code than the recursive solution but is faster since far fewer function calls are made.
public String withoutString(String base, String remove) {
int remIdx = 0;
int remLen = remove.length();
remove = remove.toLowerCase();
while (true) {
remIdx = base.toLowerCase().indexOf(remove);
if (remIdx == -1)
break;
base = base.substring(0, remIdx) + base.substring(remIdx + remLen);
}
return base;
}
I just ran your code in an IDE. It compiles correctly and matches all tests shown on codingbat. There must be some bug with codingbats test cases.
If you are curious, this problem can be solved with a single line of code:
public String withoutString(String base, String remove) {
return base.replaceAll((?i) + remove, ); //String#replaceAll(String, String) with case insensitive regex.
}
Regex explaination:
The first argument taken by String#replaceAll(String, String) is what is known as a Regular Expression or regex for short.
Regex is a powerful tool to perform pattern matching within Strings. In this case, the regular expression being used is (assuming that remove
is equal to IS
):
(?i)IS
This particular expression has two parts: (?i)
and IS
.
IS
matches the string IS
exactly, nothing more, nothing less.
(?i)
is simply a flag to tell the regex engine to ignore case.
With (?i)IS
, all of: IS
, Is
, iS
and is
will be matched.
As an addition, this is (almost) equivalent to the regular expressions: (IS|Is|iS|is)
, (I|i)(S|s)
and [Ii][Ss]
.
EDIT
Turns out that your output is not correct and is failing as expected. See: dansalmos answer.
string – Java codingbat help – withoutString
public String withoutString(String base, String remove) {
String temp = base.replaceAll(remove, );
String temp2 = temp.replaceAll(remove.toLowerCase(), );
return temp2.replaceAll(remove.toUpperCase(), );
}
Related posts