Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There's a simple solution that's much more efficient. Find the first and last occurrence of the substring and you have your answer. No need to search for all occurrences.</p> <pre><code>public int strDist(String str, String sub) { int first = str.indexOf(sub); if (first == -1) return 0; int last = str.lastIndexOf(sub); return last - first + sub.length(); } </code></pre> <p><a href="http://ideone.com/3mgbK" rel="nofollow">http://ideone.com/3mgbK</a></p> <p>The problem with your code is that you are returning the index of the last occurrence of the substring. You appear to be trying to find the 2nd last occurrence as well, and your last line should be <code>max - previous</code> at the least, but then you'd also need to add the length of the substring making it <code>max - previous + sub.length()</code>. You also need to move the declaration of <code>previous</code> outside the while loop. But then you're finding the distance between the 2nd last and last occurrences, which will fail if there aren't exactly 2 occurrences (e.g. <code>"foocatbar"</code> or <code>"catfoocatbarcat"</code>).</p> <p>Solving this recursively is a bit overkill, first and foremost because you cannot use the builtin <code>String.indexOf()</code> function. But since this is homework, here's a quick attempt:</p> <pre><code>public static int indexOf(String str, String sub, int start, int direction) { if (start &lt; 0 || start &gt; str.length() - sub.length()) return -1; if (str.substring(start, start + sub.length()).equals(sub)) return start; return indexOf(str, sub, start+direction, direction); } public static int strDistRecursive(String str, String sub) { int first = indexOf(str, sub, 0, 1); if (first == -1) return 0; int last = indexOf(str, sub, str.length() - sub.length(), -1); return last - first + sub.length(); } </code></pre> <p><a href="http://ideone.com/f6bok" rel="nofollow">http://ideone.com/f6bok</a></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload