Java > String-2 > bobThere (CodingBat Solution)

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;
}

12 comments:

  1. That's probably the intended approach. However, regex works too, and is a bit shorter.

    public boolean bobThere(String str) {
    return str.matches("^.*b.b.*$");
    }

    ReplyDelete
  2. public boolean bobThere(String str) {

    if(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;
    }

    ReplyDelete
  3. Is there a solution for this problem using a While loop?

    ReplyDelete
    Replies
    1. int i = 0;
      while(i < str.length()-2) {
      if(str.charAt(i) == 'b' &&
      str.charAt(i+2) == 'b')
      return true;
      ++i;
      }
      return false;

      Delete
  4. public boolean bobThere(String str) {
    for(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;
    }

    ReplyDelete
  5. its with str.length() -2 and it works.

    ReplyDelete
  6. public boolean bobThere(String str) {
    for(int i=0;i<str.length()-2;i++){
    if(str.charAt(i)=='b' && str.charAt(i+2)=='b')
    return true;
    }
    return false;
    }

    ReplyDelete
  7. 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?

    public 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;
    }

    ReplyDelete
    Replies
    1. Botched my code somehow, it's: for(int i = 0; i<str.length(); i ++)

      Delete
  8. public boolean bobThere(String str)
    {

    return(str.matches("^.*b\\wb.*$"));
    }

    ReplyDelete
  9. public boolean bobThere(String str) {
    for(int i=0; i<str.length()-2;i++){
    if(str.charAt(i)=='b'&&str.charAt(i+2)=='b')return true;
    }return false;
    }

    ReplyDelete