提问人:Dia Aw 提问时间:9/15/2023 最后编辑:Mark RotteveelDia Aw 更新时间:9/16/2023 访问量:76
返回用字符括起来的子字符串的递归方法
Recursive method to return substring enclosed in characters
问:
我不能使用其他方法或添加参数,只能递归调用该方法。我真的不明白如何处理这个问题。我有点挣扎,把我的思想包裹在递归上,所以对我来说是赤裸裸的。
子字符串将括在第一个和最后一个字符之间。有人可以指导我吗?除了我的基本情况之外,我知道我所掌握的东西是不对的。我觉得我并不完全理解每一步都在发生什么。
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);
}
答:
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);
}
这应该允许您使用递归正确提取包含在第一个和最后一个字符之间的子字符串。
评论
theSub("hello[there]world", '[', ']')