-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquestion24.java
More file actions
39 lines (34 loc) · 1.25 KB
/
question24.java
File metadata and controls
39 lines (34 loc) · 1.25 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
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class question24 {
public static void main(String[] args) {
String input = "ABC";
System.out.println(generatePermutations(input));
}
private static List<String> generatePermutations(String str) {
List<String> permutations = new ArrayList<>();
permutations.add(str);
for (int i = 0; i < str.length(); i++) {
List<String> newPermutations = new ArrayList<>();
for (String perm : permutations) {
for (int j = 0; j < perm.length(); j++) {
String swapped = swap(perm, i, j);
if (!newPermutations.contains(swapped)) {
newPermutations.add(swapped);
}
}
}
permutations.addAll(newPermutations);
}
Collections.sort(permutations);
return permutations;
}
private static String swap(String str, int i, int j) {
char[] charArray = str.toCharArray();
char temp = charArray[i];
charArray[i] = charArray[j];
charArray[j] = temp;
return new String(charArray);
}
}