-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathPermuteString.java
More file actions
40 lines (35 loc) · 1.06 KB
/
PermuteString.java
File metadata and controls
40 lines (35 loc) · 1.06 KB
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
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class PermuteString {
public static void main(String[] args) {
String str = "ABC";
int n = str.length();
List<String> result = permute(str, 0, 2);
for (String permutation : result) {
System.out.println(permutation);
}
}
public static List<String> permute(String str, int l, int r) {
List<String> result = new ArrayList<>();
if (l == r)
result.add(str);
else {
for (int i = l; i <= r; i++) {
str = swap(str, l, i);
List<String> temp = permute(str, l + 1, r);
result.addAll(temp);
str = swap(str, l, i);
}
}
return result;
}
public static 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);
}
}