【问题标题】:Recursive implementation of indexOfindexOf的递归实现
【发布时间】:2020-08-13 12:28:41
【问题描述】:

我已经在这里和其他地方阅读了许多以前的问题,但我还没有找到我需要的东西。 我需要编写 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】:

    如果你不想要局部变量,你需要在内部方法中进行递归。

    优点是速度要快得多,因为它不必创建新的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);
    }
    

    【讨论】:

      【解决方案2】:

      您链接的答案似乎是一个不错的答案...我建议只需将其中使用的变量的实例替换为调用变量存储的方法即可。

      下面我简单的编辑一下代码:

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

      【讨论】:

      • 完美!非常感谢
      • 进行slow递归调用两次,只是为了消除一个局部变量,是BAD.
      • 我知道可能有更快的解决方案,但我被要求没有变量。你的也是有效的
      猜你喜欢
      • 2016-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-07
      • 2014-04-15
      • 2019-05-19
      • 2023-04-10
      • 1970-01-01
      相关资源
      最近更新 更多