Computer >> Máy Tính >  >> Lập trình >> Java

Chương trình Java để tìm tất cả các tập con của một chuỗi

Trong bài này, chúng ta sẽ hiểu cách tìm tất cả các tập con của một chuỗi. Chuỗi là một kiểu dữ liệu chứa một hoặc nhiều ký tự và được đặt trong dấu ngoặc kép (“”). Một phần hoặc một tập hợp con của chuỗi được gọi là chuỗi con.

Dưới đây là một minh chứng về điều tương tự -

Giả sử đầu vào của chúng tôi là -

The string is defined as: JVM

Đầu ra mong muốn sẽ là -

The subsets of the string are:
J
JV
JVM
V
VM
M

Thuật toán

Step 1 - START
Step 2 - Declare namely
Step 3 - Define the values.
Step 4 - Initialize a temporary variable to increment after every iteration.
Step 5 - Iterate through the length of the string using two nested loops.
Step 6 - Find substring between a given range, and increment the temporary variable after every iteration.
Step 7 - Display the substrings using a loop.
Step 8 - Stop

Ví dụ 1

Ở đây, chúng tôi liên kết tất cả các hoạt động với nhau trong hàm "main".

public class Demo {
   public static void main(String[] args) {
      String input_string = "JVM";
      int string_length = input_string.length();
      int temp = 0;
      System.out.println("The string is defined as: " +input_string);
      String string_array[] = new String[string_length*(string_length+1)/2];
      for(int i = 0; i < string_length; i++) {
         for(int j = i; j < string_length; j++) {
            string_array[temp] = input_string.substring(i, j+1);
            temp++;
         }
      }
      System.out.println("The subsets of the string are: ");
      for(int i = 0; i < string_array.length; i++) {
         System.out.println(string_array[i]);
      }
   }
}

Đầu ra

The string is defined as: JVM
The subsets of the string are:
J
JV
JVM
V
VM
M

Ví dụ 2

Ở đây, chúng tôi đóng gói các hoạt động thành các hàm thể hiện lập trình hướng đối tượng.

public class Demo {
   static void subsets(String input_string){
      int string_length = input_string.length();
      int temp = 0;
      String string_array[] = new String[string_length*(string_length+1)/2];
      for(int i = 0; i < string_length; i++) {
         for(int j = i; j < string_length; j++) {
            string_array[temp] = input_string.substring(i, j+1);
            temp++;
         }
      }
      System.out.println("The subsets of the string are: ");
      for(int i = 0; i < string_array.length; i++) {
         System.out.println(string_array[i]);
      }
   }
   public static void main(String[] args) {
      String input_string = "JVM";
      System.out.println("The string is defined as: " +input_string);
      subsets(input_string);
   }
}

Đầu ra

The string is defined as: JVM
The subsets of the string are:
J
JV
JVM
V
VM
M