Skip to content

Commit 2ce8584

Browse files
authored
Update Permutation.java
1 parent 8ee98d4 commit 2ce8584

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -1 +1,44 @@
1+
import java.util.Scanner;
2+
import static java.lang.System.*;
3+
4+
public class Permutation
5+
{
6+
public static void main(String[] args)
7+
{
8+
Scanner sc = new Scanner(System.in);
9+
String s = sc.nextLine();
10+
int len = s.length();
11+
out.println("The string is " + s);
12+
permutation(s, 0, len);
13+
}
14+
15+
public static void permutation(String str, int start, int end)
16+
{
17+
//Prints the permutations
18+
if (start == end-1)
19+
System.out.println(str);
20+
else
21+
{
22+
for (int i = start; i < end; i++)
23+
{
24+
//Swapping the string by fixing a character
25+
str = swapString(str,start,i);
26+
//Recursively calling function generatePermutation() for rest of the characters
27+
permutation(str,start+1,end);
28+
//Backtracking and swapping the characters again.
29+
str = swapString(str,start,i);
30+
}
31+
}
32+
}
33+
34+
public static String swapString(String a, int i, int j)
35+
{
36+
char[] b =a.toCharArray();
37+
char ch;
38+
ch = b[i];
39+
b[i] = b[j];
40+
b[j] = ch;
41+
return String.valueOf(b);
42+
}
43+
}
144

0 commit comments

Comments
 (0)