-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReturnPermutationsOfAString.java
More file actions
57 lines (48 loc) · 1.3 KB
/
ReturnPermutationsOfAString.java
File metadata and controls
57 lines (48 loc) · 1.3 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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// Return Permutations of a String
// Hard
// Score
// 0/600
// Average time to solve is 60m
// Problem statement
// Given a string, find and return all the possible permutations of the input
// string.
// Note :
// The order of permutations are not important.
// Sample Input :
// abc
// Sample Output :
// abc
// acb
// bac
// bca
// cab
// cba
import java.util.ArrayList;
public class solution {
public static String[] permutationOfString(String input) {
// Write your code here
ArrayList<String> output = new ArrayList<>();
helper(input.toCharArray(), 0, output);
String[] result = new String[output.size()];
for (int i = 0; i < output.size(); i++) {
result[i] = output.get(i);
}
return result;
}
public static void helper(char input[], int index, ArrayList<String> output) {
if (index == input.length - 1) {
output.add(new String(input));
} else {
for (int i = index; i < input.length; i++) {
swap(input, index, i);
helper(input, index + 1, output);
swap(input, index, i);
}
}
}
public static void swap(char input[], int i, int j) {
char temp = input[i];
input[i] = input[j];
input[j] = temp;
}
}