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";
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;
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;
}
}
}
if(hasBAB(str.substring(0,halfWay -1)))
return true;
if(hasBAB(str.substring(halfWay, str.length())))
return true;
return false;
}