Skip to content

Commit aaa3343

Browse files
authored
Create StringPermutations.java
1 parent 565640f commit aaa3343

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

Hard-Level/StringPermutations.java

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/*
2+
Write a program which prints all the permutations of a string in alphabetical order. We consider that digits < upper case letters < lower case letters. The sorting should be performed in ascending order.
3+
*/
4+
5+
import java.io.*;
6+
import java.util.*;
7+
public class Main {
8+
static List<String> a = new ArrayList<String>();
9+
public static void main (String[] args) throws IOException {
10+
BufferedReader br = new BufferedReader(new FileReader(new File(args[0])));
11+
String line;
12+
while ((line = br.readLine()) != null) {
13+
a.clear();
14+
Main.permute3(line);
15+
Collections.sort(a, new Comparator<String>() {
16+
@Override
17+
public int compare(String s1, String s2) {
18+
return s1.compareTo(s2);
19+
}
20+
});
21+
System.out.print(a.get(0));
22+
for (int i = 1; i < a.size(); i++) {
23+
System.out.print("," + a.get(i));
24+
}
25+
System.out.println();
26+
}
27+
br.close();
28+
}
29+
public static void permute3 (String s) {
30+
permute3("",s);
31+
32+
}
33+
private static void permute3 (String p, String s) {
34+
if (s.length()==0) {
35+
a.add(p);
36+
}
37+
else {
38+
for (int i = 0; i < s.length(); i++) {
39+
permute3(p+s.charAt(i), s.substring(0, i) + s.substring(i+1, s.length()));
40+
}
41+
}
42+
43+
}
44+
}

0 commit comments

Comments
 (0)