使用递归生成给定字符串的所有子字符串

时间:2012-11-02 14:57:04

标签: java string recursion substring

我应该首先说这里有类似的问题但是对于我的任务,我不能使用任何循环,所有这些问题的答案都使用循环。因此,使用java 6和recursion生成给定字符串的所有子字符串。例如你给定的String word =“Ralph”;我需要将输出格式化为这样。

Ralph
Ralp
Ral
Ra
R
alph
alp
al
a
lph
lp
l
ph
h

这是我的生成方法

    //written by Justin Tew<BR>

public static void generate(String word) 
{


    //base case... wtf is the base case here?
    //idk bout this 
    if (word.length() == 1)
    {
        System.out.println(word);
        return;
    }


    //recursive case
    if (word.length() != 0)
    {

        System.out.println(word);
        generate(word.substring(0, word.length()-1)); //gets the first 5 substrings
    }

输出:

Ralph
Ralp
Ral
ra
r

在我看来,这个电话,generate(word.substring(1, word.length()-1));应该得到接下来的5个,但它不会得到非常奇怪的输出......

有什么想法吗?

6 个答案:

答案 0 :(得分:2)

这两个答案都非常正确。我刚刚添加了一个名为suffixGen的新方法:

public static void suffixGen(String word)
{
    if (word.length() > 1)
    {
        generate(word);
        suffixGen(word.substring(1));
    }

}

在我的主要内容中,我只是致电suffixGen而不是generate,它会让我获得理想的结果。

答案 1 :(得分:1)

不是递归单词的字母,而是可以递归单词长度。例如,在递归的顶层,您可以找到所有带有word.length()个字母的子字符串,然后是word.length() - 1个字母,依此类推。这可能需要两个递归方法,一个循环遍历字长,一个循环遍历该长度的所有可能的子串。

答案 2 :(得分:1)

听起来你已经完成了大部分工作。只需编写另一个递归方法generateSuffix(word)

  • 首先致电generate(word)
  • 然后使用最长的单词后缀调用generateSuffix()

您仍然需要与生成中的内容类似的基本案例。

答案 3 :(得分:1)

您不需要辅助方法,如果您将其他字符串传递给方法,只需将其值作为空白传递,如下面的方法调用所示:

    public static void substrings(String str, String temp)
    {
        if(str.length()==0)
        {
            System.out.println(temp); return;
        }

          substrings(str.substring(1), temp+str.substring(0,1));
          substrings(str.substring(1), temp);
    }

示例通话---&gt; 子串(&#34; abc&#34;,&#34;&#34;);

产生以下输出:

ABC

AB

AC

BC

B'/ P>

C

有一个不可见的字符串实际上是一个空字符串。

答案 4 :(得分:0)

尝试这样的事情

String word; 
int word_length = word.length(); //get the length of the word

for(int i=0;i<word_length;i++){
   for(int j=0; j<=word_length-i ; j++){

       String sub = word.substring(i,i+j); 
       System.out.println(sub); //print the substrings
    }

答案 5 :(得分:0)

这里一个易于阅读的解决方案

public class AllSubStrings {
    //hashset to keep a record of all the substrings
    static HashSet<String> subStrings_r=new HashSet<>();

    public static void main(String[] args) {
        String testString="Sujal";
        getSubstrings_r(testString);
        System.out.println("RECURSION ->"+subStrings_r);
    }

    public static void getSubstrings_r(String testString){
        _getSubstrings_r(testString, 0, testString.length());
    }

    public static void _getSubstrings_r(String testString,int start,int end){
        if(start==end){ //base condition
            return;
        }
        subStrings_r.add(testString.substring(start, end));
        //start getting substrings from left to right
        _getSubstrings_r(testString,start+1,end); 
        //start getting substrings from right to left
        _getSubstrings_r(testString,start,end-1);
    }

}