2014-02-26 69 views
-2

我想递归添加一个字符串之间的短划线,但它不工作,它给我一个堆栈溢出错误。以下是我的代码:递归字符串操作期间堆栈溢出错误

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; 
    } 


} 
+8

'word'永远不会改变,你的递归不会结束。 – Maroun

+6

'(stringLength - stringLength)+ 1'总是会给你一个 – turbo

+0

-1的错误标题。 – Kai

回答

3

在编写递归算法时,您需要考虑两件事情。

  1. 我的最终状态是什么?
  2. 如何减少问题的复杂性?

在你的情况,你已经正确隔离了结束状态:如果你传递了一个长度为1的字符串,那么你不需要做任何事情。

第二阶段是你感到困惑的地方。

为了所有字符之间递归加连字符,您需要:

  1. 起飞的第一个字符
  2. 添加一个连字符
  3. 运行的字符串的其余部分全部算法

下面的代码应说明这一点:

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)); 
    } 
} 
+0

ERMAGEERRD,这个工程。非常感谢:D – Noob

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; 
    } 
} 

没有彻底虽然测试。

+0

无效。虽然原因可能是由我的垃圾代码造成的。 – Noob