indexOf [JAVA]的递归实现

问题描述 投票:1回答:1

我已经在这里和其他地方阅读过很多以前的问题,但是我没有找到我需要的东西。我需要编写indexOf的递归实现。问题是我不能使用任何局部变量,而只能输入一个字符串和一个字符。

该方法应返回一个介于0和字符串长度之间的值-如果找到了char,则返回1,否则返回-1。我知道实际的'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);
    }                                  
}

我特别看到了this,但是可以不带变量地编写它吗?谢谢

java indexof
1个回答
0
投票

您链接的答案似乎是一个很好的答案……我建议您简单地用变量存储方法来替换其中使用的变量的实例。

下面我简单地编辑代码:

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));
}


0
投票

看起来像这样:

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

    if (c== s.charAt(0)) {
        return 0;
    }
    if (s.length()==1) {
        return -1;
    }
    int i = indexOf(s.substring(1), c);

    if (i != -1) return 1 + i;

    return -1;
}
© www.soinside.com 2019 - 2024. All rights reserved.