java使用递归查找字符串中的子字符串 [英] java look for a substring in a string using recursion
本文介绍了java使用递归查找字符串中的子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
此代码不起作用.请帮助修复它......................................……………………………………………………………………………………………………………………………………………………………………...................
This code doesn't work. Help fix it please.................................................................................................................
/**
Recursive method for looking for a substring in a string.
@param text look in
@param target look for as substring
@return true if target is a substring of text
*/
public static boolean find(String text, String target)
{
//-----------Start below here. To do: approximate lines of code = 4
// 1. base case: null
if (text == null) {return false;}
//2. base case: target too long
if (target.length() > text.length()) {return false;}
//3. base case: same length
if (text.length() == target.length()) {return false;}
//4. base case: startsWith OR 5. recursive case
return true;
}
推荐答案
试试这个
/**
Recursive method for looking for a substring in a string.
@param text look in
@param target look for as substring
@return true if target is a substring of text
*/
public static boolean find(String text, String target)
{
//-----------Start below here. To do: approximate lines of code = 4
// 1. base case: null
if (text == null || target == null) {return false;} // added target null check
//2. base case: target too long
if (target.length() > text.length()) {return false;}
//3. base case: same length
if (text.length() == target.length()) {return text.equals(target);}
//4. base case: startsWith OR 5. recursive case
return text.startsWith(target) || find(text.substring(1) , target);
}
这篇关于java使用递归查找字符串中的子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文