Trong bài viết này, chúng ta sẽ hiểu cách tìm tất cả các tập con (subsets) của một String. String là kiểu dữ liệu chứa một hoặc nhiều ký tự và được bao quanh bởi dấu ngoặc kép (" "). Một phần hoặc tập con của string được gọi là substring.
Minh họa dưới đây:
Giả sử đầu vào là:
The string is defined as: JVM
Đầu ra mong muốn:
The subsets of the string are: J JV JVM V VM M
Thuật toán
Bước 1 - BẮT ĐẦU Bước 2 - Khai báo biến Bước 3 - Định nghĩa giá trị Bước 4 - Khởi tạo biến tạm tăng sau mỗi lần lặp Bước 5 - Duyệt độ dài string bằng hai vòng lặp lồng nhau Bước 6 - Tìm substring giữa khoảng cho trước, tăng biến tạm sau mỗi lần lặp Bước 7 - Hiển thị substring bằng vòng lặp Bước 8 - DỪNG
Ví dụ 1
Gom thao tác dưới '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]);
}
}
}
Kết quả
The string is defined as: JVM The subsets of the string are: J JV JVM V VM M
Ví dụ 2
Đóng gói thao tác vào 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);
}
}
Kết quả
The string is defined as: JVM The subsets of the string are: J JV JVM V VM M