简体   繁体   English

indexOf的递归实现

[英]Recursive implementation of indexOf

I've already read many previous questions here and elsewhere, but I haven't found what I need.我已经在这里和其他地方阅读了许多以前的问题,但我还没有找到我需要的东西。 I need to write a recursive implementation of indexOf.我需要编写 indexOf 的递归实现。 The problem is that I can't use any local variables and have to give as input only a string and a char.问题是我不能使用任何局部变量,并且必须只提供一个字符串和一个字符作为输入。

The method should return a value between 0 and the length of the string - 1 if the char has been found or -1 if it is not there.该方法应该返回一个介于 0 和字符串长度之间的值 - 如果找到了 char,则返回 1,如果不存在,则返回 -1。 I know the actual 'indexOf' allows you to search for a string too, but this method is simplified.我知道实际的“indexOf”也允许您搜索字符串,但这种方法被简化了。

I tried this but it's quite stupid since I used the real indexOf :我试过这个,但它很愚蠢,因为我使用了真正的indexOf

public static int indexOf(String s, char c){

    if(s.indexOf(c) < 0){       // I'd like to change this
        return -1;
    }

    if (s.length() == 0)        //base case #1
    {                           
        return -1;              
    } 
    else if (s.charAt(0) == c)  //base case #2
    {                           
        return 0;               
    }
    else {
        return 1 + indexOf(s.substring(1), c);
    }                                  
}

I saw this in particular, but is it possibile to write it without variables?我特别看到了这一点,但是可以在没有变量的情况下编写它吗? Thanks谢谢

If you don't want local variables, you need to do the recursion in an internal method.如果您不想要局部变量,则需要在内部方法中进行递归。

Advantage is that it's a lot faster, since it doesn't have to create new String objects, and the logic is tail-recursive, if used with a language that optimizes that.优点是速度要快得多,因为它不必创建新的String对象,并且逻辑是尾递归的,如果与优化它的语言一起使用的话。

public static int indexOf(String s, char c) {
    return indexOf0(s, c, 0);
}
private static int indexOf0(String s, char c, int index) {
    if (index == s.length())
        return -1;
    if (s.charAt(index) == c)
        return index;
    return indexOf0(s, c, index + 1);
}

The answer that you linked seems to be a good one... I recommend simply replacing the instances of the variable used in it with the method call the variable stores.您链接的答案似乎是一个很好的答案...我建议只需将其中使用的变量实例替换为调用变量存储的方法即可。

Below I simply edit the code:下面我简单的编辑一下代码:

public static int indexOf(char ch, String str) {
    // Returns the index of the of the character ch

    if (str == null || str.equals("")) {
        // base case: no more string to search; return -1
        return -1;
    } else if (ch == str.charAt(0)) {
        // base case: ch is at the beginning of str; return 0
        return 0; 
    }

    return indexOf(ch, str.substring(1)) == -1 ? -1 : 1 + indexOf(ch, str.substring(1));
}

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

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