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

编程入门 行业动态 更新时间:2024-10-13 22:22:28
本文介绍了使用递归生成给定字符串的所有子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我应该首先说这里有类似的问题,但是对于我正在进行的任务,我不能使用任何循环,所有这些问题的答案都使用循环。因此,使用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.

更多推荐

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

本文发布于:2023-11-30 07:12:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649130.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:递归   字符串

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!