Java教程

Java查找字符串的所有子集

在此程序中,需要打印字符串的所有子集。字符串的子集是字符串中存在的字符或一组字符。
字符串的所有可能子集将为n(n + 1)/2。
例如,字符串" FUN"的所有可能子集将为F,U,N,FU,UN,FUN。
要完成此程序,我们需要运行两个for循环。外循环用于保持第一个字符的相对位置,第二循环用于创建所有可能的子集并逐个打印它们。
以下是程序的算法。

算法

步骤1: START 步骤2: DEFINE string str ="FUN" 步骤3: 定义 len = str.length() 步骤4: SET temp = 0 步骤5: DEFINE字符串数组,其长度为: len *(len + 1)/2 步骤6: SET i = 0。直到i < len 重复步骤7至步骤11 步骤7: SET j = 1。直到j < len 重复步骤8至步骤10 步骤8: arr [temp] = str.substring(i,j + 1) 步骤9: temp = temp + 1 步骤10: j = j + 1 步骤11: i = i +1 步骤12: 打印("给定字符串的所有子集为: ") 步骤13: SET i = 0 步骤14: ,直到i < arr.length 重复第14步 步骤14: 打印arr [i] 步骤15: END

程序:

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
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4