使用递归生成给定字符串的所有子字符串 [英] Using recursion to generate all substrings of a given string

查看:127
本文介绍了使用递归生成给定字符串的所有子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I should start off by saying there are similar questions asked here but for the assignment i am on i cannot use any loops and all the answers to these questions use loops. So Use java 6 and recursion to generate all the substrings of a given string. For example your given String word = "Ralph"; i need the output to be formatted like this.

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

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

In my mind this call, generate(word.substring(1, word.length()-1)); should get the next 5 but it doesn't it gets very weird output...

任何想法?

推荐答案

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

Both the 2 answers were pretty much right. I just added a new method called suffixGen:

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

}

在我的主要部分我只是打电话 suffixGen 而不是生成,它会得到我想要的结果。

and in my main I just call suffixGen instead of generate and it gets me the desired results.

这篇关于使用递归生成给定字符串的所有子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆