-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathallAnagrams.java
More file actions
40 lines (36 loc) · 1.09 KB
/
allAnagrams.java
File metadata and controls
40 lines (36 loc) · 1.09 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
/**
* Given a single input string, write a function that produces all possible anagrams
* of a string and outputs them as an ArrayList.
* Example: anagrams('def') -> ['def', 'dfe', 'edf', 'efd', 'fde', 'fed']
*/
import java.util.ArrayList;
public class allAnagrams {
//
public static ArrayList<String> anagrams(String remaining, String current, ArrayList<String> results){
if(remaining.length() == 0){
results.add(current);
} else {
for(int i = 0; i < remaining.length(); i++){
String newStr = current + remaining.charAt(i);
String newRemaining = "";
for(int j=0; j < remaining.length(); j++){
if( i != j){
newRemaining += remaining.charAt(j);
}
}
anagrams(newRemaining, newStr, results);
}
}
return results;
}
// Overload anagrams class for ease of use
public static ArrayList<String> anagrams(String start){
return anagrams(start, "", new ArrayList<String>());
}
public static void main(String[] args){
ArrayList<String> result = anagrams("def");
for( int i = 0; i < result.size(); i++ ){
System.out.println(result.get(i));
}
}
}