Problem:
Return true if the given string contains a "bob" string, but where the middle 'o' char can be any char.
bobThere("abcbob") → true
bobThere("b9b") → true
bobThere("bac") → false
Solution:
public boolean bobThere(String str) { int len = str.length(); for (int i = 0; i < len - 2; i++) { if (str.charAt(i) == 'b' && str.charAt(i+2) == 'b') return true; } return false; }
That's probably the intended approach. However, regex works too, and is a bit shorter.
ReplyDeletepublic boolean bobThere(String str) {
return str.matches("^.*b.b.*$");
}
public boolean bobThere(String str) {
ReplyDeleteif(str.length()>2){
for(int i=0;i<str.length()-2;i++)
{
if(str.charAt(i)=='b')
{
if(str.charAt(i+2)=='b')
return true;
}
}
}
return false;
}
fails for:
DeletebobThere("bbc")
Is there a solution for this problem using a While loop?
ReplyDeleteint i = 0;
Deletewhile(i < str.length()-2) {
if(str.charAt(i) == 'b' &&
str.charAt(i+2) == 'b')
return true;
++i;
}
return false;
public boolean bobThere(String str) {
ReplyDeletefor(int i=0;i<str.length()-1;i++){
if(i+2<str.length() && str.charAt(i)=='b' && str.charAt(i+2)=='b'){
return true;
}
}
return false;
}
its with str.length() -2 and it works.
ReplyDeletepublic boolean bobThere(String str) {
ReplyDeletefor(int i=0;i<str.length()-2;i++){
if(str.charAt(i)=='b' && str.charAt(i+2)=='b')
return true;
}
return false;
}
Probably a bit messy, but why does my code not work for "bobThere("abcdefb") → false"? Is it better to use charAt instead of substring? And why?
ReplyDeletepublic boolean bobThere(String str) {
for(int i = 0; i= 3) {
if(str.substring(i).contains("b") && str.substring(i+2).contains("b")){
return true;
}
return false;
}
}
return false;
}
Botched my code somehow, it's: for(int i = 0; i<str.length(); i ++)
Deletepublic boolean bobThere(String str)
ReplyDelete{
return(str.matches("^.*b\\wb.*$"));
}
public boolean bobThere(String str) {
ReplyDeletefor(int i=0; i<str.length()-2;i++){
if(str.charAt(i)=='b'&&str.charAt(i+2)=='b')return true;
}return false;
}