forked from sambit77/Algoexpert-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStringPermutation.java
More file actions
43 lines (41 loc) · 1022 Bytes
/
StringPermutation.java
File metadata and controls
43 lines (41 loc) · 1022 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
//Program to find all the permutations of a String
//Time Complexity O(n*n!)
//Space Complexity O(1)
import java.util.*;
class A
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("enter the String");
String str = sc.nextLine();
calculate(str,0,str.length()-1);
}
public static String swap(String str,int a , int b)
{
//swap characters at index a and index b in a String
char temp;
char[] crr = str.toCharArray();
temp = crr[a];
crr[a] = crr[b];
crr[b] = temp;
return String.valueOf(crr);
}
public static void calculate(String str , int start , int end)
{
if(start==end)
{
System.out.println(str);
}
else
{
for(int i = start ; i <= end ; i++)
{
//swap the first character of the received string with every other charactre
String swapped = swap(str,start,i);
//recursively do it for all other charcters in the String
calculate(swapped,start+1,end);
}
}
}
}