返回用字符括起来的子字符串的递归方法

Recursive method to return substring enclosed in characters

提问人:Dia Aw 提问时间:9/15/2023 最后编辑:Mark RotteveelDia Aw 更新时间:9/16/2023 访问量:76

问:

我不能使用其他方法或添加参数,只能递归调用该方法。我真的不明白如何处理这个问题。我有点挣扎,把我的思想包裹在递归上,所以对我来说是赤裸裸的。

子字符串将括在第一个和最后一个字符之间。有人可以指导我吗?除了我的基本情况之外,我知道我所掌握的东西是不对的。我觉得我并不完全理解每一步都在发生什么。

public static String theSub(String str, char first, char last) {
    if (str.length() == 0 ) {
        return str;
    }
    else if (str.charAt(0)==first) {
        return str.substring(1, str.length() - 1);
    }
  //infinite recursion..
    return theSub(str,first,last);
}
java 子字符串 无限递归

评论

3赞 tgdavies 9/15/2023
Stack Overflow 不是一个代码编写服务,但我会提示递归过程中的每个步骤都必须接近基本情况,因此,正如您所说,将相同的参数值传递给递归调用,这将为您提供无限递归。
2赞 Old Dog Programmer 9/15/2023
如果你要改进对问题实际情况的描述,这将有所帮助——这就是你的代码要解决的问题。参加导览,并阅读如何提出一个好问题,以及链接到的页面可能会有所帮助。
1赞 VGR 9/15/2023
请编辑您的问题,并提供一个或多个输入参数和预期输出的示例。应该返回“那里”吗?theSub("hello[there]world", '[', ']')

答:

0赞 Reilas 9/15/2023 #1

"...子字符串将括在第一个和最后一个字符之间。有人可以指导我吗?除了我的基本情况之外,我知道我所掌握的东西是不对的。我觉得我并不完全理解每一步都在发生什么。..."

例如,如果字符串是“f(f(f(x)))”,并且您想要获取 x

从本质上讲,当第一个最后一个都存在时,获取子字符串并进行递归调用。

public static String theSub(String str, char first, char last) {
    if (str.length() == 0 ) return str;
    int i = str.indexOf(first), j = str.lastIndexOf(last);
    if (i == -1 || j == -1) return str;
    return theSub(str.substring(i + 1, j), first, last);
}
0赞 Sarah 9/15/2023 #2

我将引导您完成创建递归方法的步骤,该方法提取包含在第一个字符和最后一个字符之间的子字符串。

public static String theSub(String str, char first, char last) {
    // Base case 1: If the input string is empty, return an empty string.
    if (str.length() == 0) {
        return "";
    }

    // Base case 2: If the first character of the string is 'last', return an empty string.
    if (str.charAt(0) == last) {
        return "";
    }

    // Base case 3: If the first character of the string is 'first', call the helper function.
    if (str.charAt(0) == first) {
        return extractSubstring(str.substring(1), first, last);
    }

    // Recursive case: Keep looking for the 'first' character.
    return theSub(str.substring(1), first, last);
}

// Helper function to extract the substring between 'first' and 'last' characters.
private static String extractSubstring(String str, char first, char last) {
    // Base case: If the string is empty, return an empty string.
    if (str.length() == 0) {
        return "";
    }

    // If the current character is 'last', we've reached the end of the substring.
    if (str.charAt(0) == last) {
        return "";
    }

    // Recursively build the substring.
    return str.charAt(0) + extractSubstring(str.substring(1), first, last);
}

这应该允许您使用递归正确提取包含在第一个和最后一个字符之间的子字符串。