简体   繁体   中英

Implement my own recursive version of the indexOf method

So I'm trying to write recursive method indexOf which returns the starting index of the first occurrence of the second String inside the first String (or -1 if not found).For example, the call of indexOf (“Barack Obama”, “bam”) would return 8. Also I know that String class has method IndexOf, but I don't want to use it.

So far this is my code:

public class MyClass {

    public static void main(String[] args) {
    }

    public static int indexOf(String s, String t) {
        return abc(s, t, 0);
    }

    public static int abc(String a, String b, int c) {
        if ((a.length() - c) < b.length()) {
            return -1;
        } else if (b.equals(a.substring(c, c + 3))) {
            return c;

        } else {

        }
    }
}

It depends how much of the library you want to use.

One option is:

int indexOf(String container, String text, int index) {
  //Too short container
  if (container.length() < text.length()) return -1; 
  //found
  else if (container.startsWith(text)) return index;
  //keep searching
  else return indexOf(container.substring(1), text, index+1);
}
indexOf("banana", "nana", 0) == 2;

If you don't want to use .startsWith, then you need to implement your own version. A very good exercise would be to try and do this without ever using the .substring method, which is terrible (as it creates a copy of the string, O(n) space/time performance), and which is not needed for this task (use .charAt)

You can also split the official method indexOf from its recursive call that includes the index for more clarity).

You should think carefully about edge cases too :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM