-
Notifications
You must be signed in to change notification settings - Fork 6
/
StringPermutation.java
49 lines (41 loc) · 1.08 KB
/
StringPermutation.java
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
import java.util.ArrayList;
import java.util.List;
//read recursive version of permutation from https://www.youtube.com/watch?v=MQcwxQK2DPA
public class StringPermutation
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
String input = "abhiSheK";
List<String> permute = StringPermutation.permute(input);
for (String string : permute)
{
System.out.println("--> "+string);
}
}
public static List<String> permute(String str){
ArrayList<String> permutations = new ArrayList<String>();
if(str == null){
return null;
}
else if(str.length() == 0){
permutations.add("");
return permutations;
}
char ch = str.charAt(0);
String remainder = str.substring(1);
List<String> wordList = permute(remainder);
for (String word : wordList)
{
for(int i=0;i<=word.length();i++){
permutations.add(insertCharAt(word,ch,i));
}
}
return permutations;
}
public static String insertCharAt(String word, char ch, int i){
String start = word.substring(0,i);
String end = word.substring(i);
return start + ch + end;
}
}