下面是调用递归方法的代码:于issubstring递归方法
if (isSubstring(str1, str2))
System.out.println ("\"" + str1 + "\" is a substring of " +
"\"" + str2 + "\"");
else
System.out.println ("\"" + str1 + "\" is not a substring of " +
"\"" + str2 + "\"");
这是我到目前为止已经完成了方法,它几乎工作:
public static boolean isSubstring(String str, String target)
{
if (target.length() == 0)
return false;
if (str.equals(target))
return true;
else
return (isSubstring(str, target.substring(0,target.length()-1)));
}
所以它的工作原理如果str1作为“zzz”传递,str2作为“zzzabcdef”传递,那么它将返回true。但是,如果str2是“abczzzxx”或“abczzz”,它不会返回true。有没有人有任何建议或想法?
你的方法可能是一条线件事:'回报str.contains(目标);' – assylias
我注意到你的'如果(target.length()== 0)'声明。你可能想要对str和target进行一些空的检查。我喜欢使用'StringUtils.isBlank()'方法;看到http://commons.apache.org/lang/api-2.5/org/apache/commons/lang/StringUtils.html#isBlank(java.lang.String) –
@assylias我想重点是做递归作为练习 – maasg