File tree 1 file changed +59
-0
lines changed
1 file changed +59
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ This program will return all the subsequences of the input string in a string array;
3
+ Sample Input:
4
+ abc
5
+ Sample Output:
6
+ "" ( Empty String )
7
+ c
8
+ b
9
+ bc
10
+ a
11
+ ac
12
+ ab
13
+ abc
14
+
15
+ */
16
+
17
+ import java .util .Scanner ;
18
+
19
+ public class ReturnSubsequence {
20
+ /*
21
+ Main function will accept the given string and implement return subsequences function
22
+ */
23
+ public static void main (String [] args ) {
24
+ System .out .println ("Enter String: " );
25
+ Scanner s =new Scanner (System .in );
26
+ String givenString =s .next (); //given string
27
+ String [] subsequence =returnSubsequence (givenString ); //calling returnSubsequence() function
28
+ System .out .println ("Subsequences : " );
29
+ for (int i =0 ;i <subsequence .length ;i ++) //print the given array of subsequences
30
+ {
31
+ System .out .println (subsequence [i ]);
32
+ }
33
+ }
34
+ /*
35
+ Recursive function to return Subsequences
36
+ */
37
+ private static String [] returnSubsequence (String givenString ) {
38
+ if (givenString .length ()==0 ) // If string is empty we will create an array of size=1 and insert "" (Empty string) in it
39
+ {
40
+ String [] ans =new String [1 ];
41
+ ans [0 ]="" ;
42
+ return ans ;
43
+
44
+ }
45
+ String [] SmallAns =returnSubsequence (givenString .substring (1 )); //recursive call to get subsequences of substring starting from index position=1
46
+
47
+ String [] ans =new String [2 *SmallAns .length ];// Our answer will be an array off string of size=2*SmallAns
48
+ int i =0 ;
49
+ for (;i <SmallAns .length ;i ++)
50
+ {
51
+ ans [i ]=SmallAns [i ]; //Copying all the strings present in SmallAns to ans string array
52
+ }
53
+ for (int k =0 ;k <SmallAns .length ;k ++)
54
+ {
55
+ ans [k +SmallAns .length ]=givenString .charAt (0 )+SmallAns [k ]; // Insert character at index=0 of the given substring in front of every string in SmallAns
56
+ }
57
+ return ans ;
58
+ }
59
+ }
You can’t perform that action at this time.
0 commit comments