简体   繁体   中英

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. 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. I know the actual 'indexOf' allows you to search for a string too, but this method is simplified.

I tried this but it's quite stupid since I used the real 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.

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

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