我正在尝试递归地在字符串之间添加一个破折号,但它不起作用,并且它给了我一个堆栈溢出错误。这是我的代码:
public static String expand (String word)
{
int stringLength = word.length ();
String expandedWord = word;
if (stringLength <= 1)
{
return expandedWord;
}
else
{
expandedWord = word.substring (0, (stringLength - stringLength) + 1) + "-" + word.substring ((stringLength - stringLength) + 1, stringLength);
stringLength++;
expand(word);
return expandedWord;
}
}
答案 0 :(得分:3)
编写递归算法时,需要考虑两件事。
在你的情况下,你已经正确地隔离了结束状态:如果你传递了一个长度为1的字符串,那么你就不需要做什么了。
第二阶段是你感到困惑的地方。
为了在所有字符之间递归添加连字符,您需要:
以下代码应注明:
public static String expand(String word)
{
if (word.length() <= 1)
{
// My end state: the input string has 0 or 1 characters - no way to add hyphens!
return word;
}
else
{
// Return the first character of word, a hyphen, and the result of the recursive algorithm
return word.substring(0, 1) + "-" + expand(word.substring(1));
}
}
答案 1 :(得分:0)
试试这个:
public static String expand (String word)
{
int stringLength = word.length ();
String expandedWord = word;
if (stringLength <= 1)
{
return expandedWord;
}
else
{
expandedWord = word.substring (0, 1) + "-" + expand(word.substring(1, stringLength));
return expandedWord;
}
}
虽未经过彻底测试。