简体   繁体   English

实现我自己的indexOf方法的递归版本

[英]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. 因此,我尝试编写递归方法indexOf ,该方法将返回第一个String内第二个String第一次出现的起始索引(如果未找到则返回-1)。例如,对indexOf的调用(“ Barack Obama”,“ bam”)将返回8。另外,我知道String类具有方法IndexOf,但我不想使用它。

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. 如果您不想使用.startsWith,则需要实现自己的版本。 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) 一个很好的练习是尝试不使用.substring方法来执行此操作,这很糟糕(因为它创建字符串的副本,O(n)时空性能),并且此任务不需要(使用.charAt)

You can also split the official method indexOf from its recursive call that includes the index for more clarity). 您也可以将官方方法indexOf从包含索引的递归调用中分离出来,以更加清楚。

You should think carefully about edge cases too :) 您也应该仔细考虑边缘情况:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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