【发布时间】:2017-07-04 23:34:32
【问题描述】:
我是一名学生,我一直在努力应对以下挑战:在不使用substring 方法和使用递归的情况下,在更大的字符串(大海捞针)中找到子字符串(针)。递归不是我的强项,但我已经解决了以下问题:
public class Contains
{
public static void main(String[] args)
{
System.out.println(contains("Java programming", "ogr", false));
}
public static boolean contains(String haystack, String needle, boolean doesContain)
{
if(haystack.length() < needle.length())
{
return false;
}
else
{
for(int i = 0; i < needle.length(); i++)
{
if(haystack.charAt(i) != needle.charAt(i))
if((i + 1) == needle.length())
{
doesContain = false;
break;
}
else
break;
else
if((i + 1) == needle.length())
{
doesContain = true;
break;
}
else
continue;
}
char[] haystackChar = haystack.toCharArray();
char[] newCharArray = new char[(haystackChar.length - 1)];
for(int j = 1; j < haystackChar.length; j++)
{
newCharArray[j - 1] = haystackChar[j];
}
String newStr = new String(newCharArray);
if(doesContain == false)
contains(newStr, needle, doesContain);
}
return doesContain;
}
}
我意识到这可能不是最好或最优雅的解决方案,但我主要只是想让它发挥作用。我一直在 Eclipse 调试器中运行它,直到在方法调用contain 期间调用if(doesContain == false) 之前,一切都按预期运行,其中doesContain 在for 循环的迭代期间设置为true。调试器显示doesContain 的值(正确)为真,并显示它跳过 if 语句并退出 else 块。然而,在那之后,它立即跳回到 else 块并且只调用对contain 的递归调用,而不是返回doesContain。然后,它继续递归工作,随后失败并返回 false,因为它现在正在搜索字符串的其余部分,其中没有“needle”。
我知道 StackOverflow 本身并不是一个“家庭作业帮助”位置,但我为学校以外的目的进行编程,我对它为什么会这样表现感到非常困惑。有谁知道它为什么这样做?我在这里遗漏了什么吗?
【问题讨论】:
-
哦,伙计,我希望我是个女孩,会收到垃圾邮件!无论如何,您的(诚然格式不正确)代码运行良好。问题是您正在丢弃递归调用的结果。将
contains(newStr, needle, doesContain);更改为return contains(newStr, needle, doesContain);,然后瞧!