java 字符串查找程序,查找字符串的所有子集的Java程序

查找字符串的所有子集的Java程序

1 说明

在此程序中,需要打印字符串的所有子集。字符串的子集是字符串中存在的字符或一组字符。

字符串的所有可能子集将为n(n + 1)/ 2。

例如,字符串“ FUN”的所有可能子集将为F,U,N,FU,UN,FUN。

要完成此程序,我们需要运行两个for循环。外循环用于保持第一个字符的相对位置,第二循环用于创建所有可能的子集并逐个打印它们。

2 算法思路

步骤1:开始

步骤2: 定义字符串str =“ FUN”

步骤3:定义len = str.length()

步骤4: SET TEMP = 0

步骤5:定义长度为len *(len + 1)/ 2的字符串数组

步骤6: SET i = 0。直到i

步骤7: SET j = 1。直到j

步骤8: arr [temp] = str.substring(i,j + 1)

步骤9: temp = temp + 1

步骤10: j = j + 1

步骤11: i = i +1

步骤12: 打印(“All subsets for given string are:”)

步骤13: SET i = 0

步骤14:重复步骤14,直到i

步骤14:列印arr [i]

步骤15:结束

3 程序实现

/**

* 一点教程网: http://www.yiidian.com

*/

public class AllSubsets {

public static void main(String[] args) {

String str = "FUN";

int len = str.length();

int temp = 0;

//Total possible subsets for string of size n is n*(n+1)/2

String arr[] = new String[len*(len+1)/2];

//This loop maintains the starting character

for(int i = 0; i < len; i++) {

//This loop adds the next character every iteration for the subset to form and add it to the array

for(int j = i; j < len; j++) {

arr[temp] = str.substring(i, j+1);

temp++;

}

}

//This loop prints all the subsets formed from the string.

System.out.println("All subsets for given string are: ");

for(int i = 0; i < arr.length; i++) {

System.out.println(arr[i]);

}

}

}

以上代码输出结果为:

All subsets for given string are:

F

FU

FUN

U

UN

N

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值