Last active
October 29, 2020 17:09
-
-
Save dstein64/e3841157343a7aeeed20d7cff435eeb3 to your computer and use it in GitHub Desktop.
Example code for a Stack Overflow comment: https://stackoverflow.com/a/64549281/1509433
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
import java.util.HashSet; | |
import java.util.List; | |
import java.util.Set; | |
public class Anagrams { | |
public static List<String> anagrams(String s) { | |
List<String> output = new ArrayList<String>(); | |
if (s.length() == 0) | |
return output; | |
if (s.length() == 1) { | |
output.add(s); | |
return output; | |
} | |
Set<String> prefixes = new HashSet<String>(); | |
for (int i = 0; i < s.length(); ++i) { | |
String c = s.substring(i, i + 1); | |
// Skip generating repeated anagrams | |
if (prefixes.contains(c)) | |
continue; | |
prefixes.add(c); | |
// Remove char c from string s to form string s2 | |
String s2 = s.substring(0, i) + s.substring(i + 1); | |
// Calculate anagrams of s2 and append each to char c | |
List<String> anagrams2 = anagrams(s2); | |
for (String anagram : anagrams2) { | |
output.add(c + anagram); | |
} | |
} | |
return output; | |
} | |
public static void main(String[] args) { | |
List<String> l = anagrams("abb"); | |
for (String s : l) { | |
System.out.println(s); // abb, bab, bba | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment