forked from tkggft/JavaClassicInterviewQuestions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPerm.java
More file actions
48 lines (38 loc) · 1.13 KB
/
Perm.java
File metadata and controls
48 lines (38 loc) · 1.13 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
import java.util.ArrayList;
import java.util.Scanner;
/**
* @auther: WJoe
* @Description:
* @Date : 21:02 2018/9/2
*/
public class Perm {
public static ArrayList<String> getPerms(String str){
if(str==null)
return null;
ArrayList<String> permutations=new ArrayList<String>();
if(str.length()==0){
permutations.add("");
return permutations;
}
char first=str.charAt(0);
String remainder=str.substring(1);
ArrayList<String> words=getPerms(remainder);
for(String word:words){
for(int i=0;i<=word.length();i++){
String s=insertCharAt(word, first, i);
System.out.println(s);
permutations.add(s);
}
}
return permutations;
}
public static String insertCharAt(String word,char c,int i){
String start=word.substring(0, i);
String end=word.substring(i);
return start+c+end;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println(getPerms(sc.nextLine()));
}
}