java 递归 字符串,Java - 使用递归从字符串创建所有子字符串

The following code in Java uses recursion to create all possible substrings from a string.

I am wondering is there a better way of coding this? I want to use recursion.

public class main {

public static void main(String[] args) {

generate("hello");

}

public static void generate(String word) {

if (word.length() == 1) {

System.out.println(word);

return;

}else{

System.out.println(word);

generate(word.substring(0, word.length()-1));

generate(word.substring(1, word.length()));

}

}

}

FAQ

Q - Why do I want to do this using recursion?

A - Because the CEO of StackOverflow says recursion is important

http://www.joelonsoftware.com/articles/ThePerilsofJavaSchools.html

解决方案

The following turned out to be the best solution:

public class recursive {

static String in = "1234";

public static void main(String[] args) {

substrings(0,1);

}

static void substrings(int start, int end){

if(start == in.length() && end == in.length()){

return;

}else{

if(end == in.length()+1){

substrings(start+1,start+1);

}else{

System.out.println(in.substring(start, end));

substrings(start, end+1);

}

}

}

}

It first checks the base case: if both start and end are equal to in.length().

Because if they are, that means there are no more substrings to be found, and the program ends.

Let's start with start=0 and end=1. They obviously don't equal in.length(), and end definitely doesn't equal in.length()+1.

Thus, substring(0,1) will be printed out, which is 1.

The next iteration of substrings will be substrings(0,2), and in.substring(0,2) will be printed, which is 12. This will continue until end == in.length()+1, which happens when the program finishes substrings(0,4) and tries to move on to substrings(0,5).

5 == in.length()+1, so when that happens, the program will do substrings(start+1,start+1), which is substrings(1,1). The process will continue with substrings(1,2), and (1,3), until (1,5) when the program will run substrings(2,2).

All of this will continue until substrings(4,4), which, at that point, the program stops.

The result looks like this:

1

12

123

1234

2

23

234

3

34

4

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值