Boolean that contains "bab"

How can I get a recursive boolean method that will check if it contains bab. I have this, but I would like to do it recursively.

public static boolean hasBAB(String str) {
      if (str.length() < 3) return false;
      if (str.substring(0,3).equals("bab"))
        return true;
      else
        return false;
    }
+1
source share
3 answers

Recursion should be considered as two parts.

1) The main case. This is a trivial case that can be easily determined. What you have is a good start to the base case. 1) String less than 3? Then return false. 2) The line starts with "bab" and then returns true.

2) Recursive case. This breaks down the problem into more subtle problems, and if you separate them reliably enough, you will have a base case.

@Logiraptro has a good example of simple recursion.

public static boolean hasBAB(String str) {
  if (str.length() < 3) return false;
  if (str.substring(0,3).equals("bab"))
    return true;
  else
    return hasBAB(str.substring(1));
}

, . , .

, .

? , , ln (n), n - . , , . 1 000 000 ! 14 .

, , .

1) , false. 2) , , true, else false. 3) , true.

, .

, "bab" , , , , .

public static boolean hasBAB(String str) {
      String searchString = "bab";

      // Base cases
      if (str.length() < searchString.length()) 
          return false;

      if (str.length() == searchString.length())
      {
          if (str.equals(searchString))
          {
              return true;
          }
          return false;
      }

      int halfWay = str.length()/2;

      // Now check for the search string over the "break"
      for (int i = 0; i < searchString.length(); i++)
      {
          int startIndex = halfWay - 1 - i;
          int endIndex = startIndex + 3;
          if (startIndex >= 0)
          {
              String substring = str.substring(startIndex, endIndex);
              if (substring.equals(searchString))
              {
                  return true;
              }
          }
      }

     // Recursive Cases 
     //  We did find the search string over the break,so break the string into two equal(ish) pieces and check those 
     if(hasBAB(str.substring(0,halfWay -1)))
         return true;

     if(hasBAB(str.substring(halfWay, str.length())))
         return true;

     return false;
}
+2
public static boolean hasBAB(String str) {
  if (str.length() < 3) return false;
  if (str.substring(0,3).equals("bab"))
    return true;
  else
    return hasBAB(str.substring(1));
}

String.contains

+5

No need for recursion;) You are looking for String.contains

public static boolena hasBAB (String str) {
    if (String.length() < 3) return false;
    else return str.contains("bab");
}
+4
source

All Articles