The following is a description of the problem:
PS: given string and non-empty substring sub, recursively compute the largest substring that starts and ends with sub and returns its length.
Examples:
strDist("catcowcat", "cat") β 9
strDist("catcowcat", "cow") β 3
strDist("cccatcowcatxx", "cat") β 9
Below is my code: (Without recursion) //, since it was difficult for me 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; }
Works for a 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 tell me what is wrong with the code, and how to return the largest substring that starts and ends on sub with the corresponding length.