Compute the Length of Largest substring that starts and ends with the same substring
Posted
by
Deepak
on Stack Overflow
See other posts from Stack Overflow
or by Deepak
Published on 2010-12-26T09:44:01Z
Indexed on
2010/12/26
9:54 UTC
Read the original article
Hit count: 421
Hi People, Below is the Problem Statement:
PS: 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
Below is my Code: (Without recursion)//since i found it hard to implement with recursion.
public int strDist(String str, String sub){
int idx = 0;
int max;
if (str.isEmpty()) max = 0;
else max=1;
while ((idx = str.indexOf(sub, idx)) != -1){
int previous=str.indexOf(sub, idx);
max = Math.max(max,previous);
idx++;
}
return max;
}
Its working for few as shown below but returns FAIL for others.
Expected This Run
strDist("catcowcat", "cat") ? 9 6 FAIL
strDist("catcowcat", "cow") ? 3 3 OK
strDist("cccatcowcatxx", "cat") ? 9 8 FAIL
strDist("abccatcowcatcatxyz", "cat") ? 12 12 OK
strDist("xyx", "x") ? 3 2 FAIL
strDist("xyx", "y") ? 1 1 OK
strDist("xyx", "z") ? 0 1 FAIL
strDist("z", "z") ? 1 1 OK
strDist("x", "z") ? 0 1 FAIL
strDist("", "z") ? 0 0 OK
strDist("hiHellohihihi", "hi") ? 13 11 FAIL
strDist("hiHellohihihi", "hih") ? 5 9 FAIL
strDist("hiHellohihihi", "o") ? 1 6 FAIL
strDist("hiHellohihihi", "ll") ? 2 4 FAIL
Could you let me whats wrong with the code and how to return the largest substring that begins and ends with sub with its respective length.
© Stack Overflow or respective owner