이 기사에서는 문자열의 모든 하위 집합을 찾는 방법을 이해할 것입니다. 문자열은 하나 이상의 문자를 포함하고 큰따옴표(" ")로 묶인 데이터 유형입니다. 문자열의 일부 또는 하위 집합을 부분 문자열이라고 합니다.
아래는 동일한 데모입니다 -
입력이 다음과 같다고 가정 -
The string is defined as: JVM
원하는 출력은 -
The subsets of the string are: J JV JVM V VM M
알고리즘
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
예시 1
여기에서 모든 작업을 '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]);
}
}
} 출력
The string is defined as: JVM The subsets of the string are: J JV JVM V VM M
예시 2
여기에서 객체 지향 프로그래밍을 나타내는 함수로 작업을 캡슐화합니다.
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);
}
} 출력
The string is defined as: JVM The subsets of the string are: J JV JVM V VM M