Skip to content

Commit ec117ef

Browse files
authored
Create Return permutations of a string
1 parent eaf8e4c commit ec117ef

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/*
2+
Given a string, find and return all the possible permutations of the input string.
3+
Note : The order of permutations are not important.
4+
5+
Sample Input :
6+
abc
7+
Sample Output :
8+
abc
9+
acb
10+
bac
11+
bca
12+
cab
13+
cba
14+
*/
15+
16+
public class solution {
17+
18+
public static String[] permutationOfString(String input){
19+
// Write your code here
20+
if (input.length()==0)
21+
return new String[1];
22+
23+
if (input.length()==1)
24+
{
25+
String[] arr = new String[1];
26+
arr[0]=input;
27+
return arr;
28+
}
29+
30+
char c=input.charAt(0);
31+
String[] temp = permutationOfString(input.substring(1));
32+
String[] output = new String[temp.length*input.length()];
33+
//System.out.println("Total number of permutations till now: "+output.length);
34+
int k=0;
35+
for (int i=0;i<temp.length;i++)
36+
{
37+
String newstr=temp[i];
38+
for (int j=0;j<newstr.length();j++)
39+
{
40+
output[k]=newstr.substring(0,j)+c+newstr.substring(j);
41+
k=k+1;
42+
}
43+
output[k]=newstr+c;
44+
k=k+1;
45+
//System.out.println(output[i]);
46+
}
47+
48+
return output;
49+
50+
}
51+
52+
}

0 commit comments

Comments
 (0)