forked from darpanjbora/Java-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAllPermutationsOfAString.java
More file actions
41 lines (35 loc) · 993 Bytes
/
AllPermutationsOfAString.java
File metadata and controls
41 lines (35 loc) · 993 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
/**
* A string of length n has n! permutation.
*/
import java.util.*;
import java.io.*;
class AllPermutationsOfAString {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String S = sc.nextLine();
int len = S.length();
AllPermutationsOfAString per = new AllPermutationsOfAString();
per.permute(S, 0, len-1);
}
public void permute(String S, int l, int r){
if (l == r)
System.out.println(S);
else{
for(int i=l; i<=r; i++){
S = swap(S, l, i);
permute(S, l+1, r);
S = swap(S, l, i);
}
}
}
//Swapping characters of a string.
public String swap(String a, int i, int j)
{
char temp;
char[] charArray = a.toCharArray();
temp = charArray[i] ;
charArray[i] = charArray[j];
charArray[j] = temp;
return String.valueOf(charArray);
}
}