The task is: Given a string and a non-empty substring sub, compute recursively the largest substring which starts and ends with sub and return its length.
Examples:
strDist("catcowcat", "cat") → 9
strDist("catcowcat", "cow") → 3
strDist("cccatcowcatxx", "cat") → 9
Can you please look at my code and tell me what is the problem with it?
public int strDist(String str, String sub)
{
if(str.length()<sub.length())
return 0;
if(str.length()==sub.length()&&str.equals(sub))
return str.length();
if(str.length()<2)
{
if(str.contains(sub))
{
return 1;
}
return 0;
}
if (str.length()==2)
{
if (sub.length()==2 && str.equals(sub))
return 2;
if (str.contains(sub))
return 1;
return 0;
}
if(str.length()>2)
{
if(str.startsWith(sub)&&str.endsWith(sub))
{
return str.length();
}
if(str.substring(0,sub.length()).equals(sub))
{
strDist(str.substring(0,str.length()-2),sub);
}
if(str.substring(str.length()-sub.length(),str.length()-1).equals(sub))
strDist(str.substring(1,str.length()-1),sub);
}
return strDist(str.substring(1,str.length()-1),sub);
}
it doesn't work for the case strDist("hiHellohihihi", "hih")
→ 5
and returns zero.
Since, others have already answered with the recursive code, I have included an O(n) solution using KMP algorithm
First, to answer your question, I found a number of issues in your code. My corrected version follows, with comments about the changes I did.
Now if I do:
I get:
Second, as I said in a comment, I see no point in using recursion here (except perhaps for the exercise). The following version of your method doesn’t, it’s much simpler and it works the same:
Finally, and this may or may not be helpful, a recursive version needs not be as complicated as yours:
It’s fine to get something to work first if you can, even if it’s not the most simple and elegant solution. When either it works or it doesn’t, is a good time to think of ways to simplify. It will make it easier to nail down the bug(s) and also ease maintenance later. Special cases, like length 1 and length 2, are often a good candidate for simplification: see if the general code already caters for them or can easily be made to.
this is my way of solving it, it is kinda similar but i find it simpler (hope it helps) :
A small solution with explanation
Your implementation is hard to follow. It would be more appropriate to describe the algorithm rather to provide the implementation.
Based on the description, below is my implementation. I think it is concise and easy to understand.
Result: