-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathStringPermutations.java
More file actions
40 lines (35 loc) · 974 Bytes
/
StringPermutations.java
File metadata and controls
40 lines (35 loc) · 974 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
#Print all the string permutations that are unique
import java.util.HashSet;
import java.util.Set;
public class RecursionProgram
{
public static void main(String args[])
{
permutations("abcd", 0, 3);
}
static Set<String> set = new HashSet<String>();
static void permutations(String s, int l, int r)
{
if(l == r)
{
if(set.contains(s)) return;
set.add(s);
System.out.println(s);
return;
}
for (int i = l; i <= r; i++)
{
s = interchangeChar(s, l, i);
permutations(s, l+1, r);
s = interchangeChar(s, l, i);
}
}
private static String interchangeChar(String s, int a, int b) {
// TODO Auto-generated method stub
char[] array = s.toCharArray();
char temp = array[a];
array[a] = array[b];
array[b] = temp;
return String.valueOf(array);
}
}