Skip to content

Instantly share code, notes, and snippets.

@calebastey
Created May 22, 2015 17:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save calebastey/3de9d819a2f087866e3d to your computer and use it in GitHub Desktop.
Save calebastey/3de9d819a2f087866e3d to your computer and use it in GitHub Desktop.
Anagram.java
import java.lang.Character;
import java.util.Set;
import java.util.HashSet;
public class Anagram {
public static void main(String [] args) {
System.out.println(nAnagrams("AdnBndAndBdaBn", "dAn"));
System.out.println(nAnagrams("AbrAcadAbRa", "cAda"));
}
static int nAnagrams(String parent, String child) {
Set children = buildCharacterSet(child);
int total = 0;
for (int i = 0; i < parent.length() - (child.length() + 1); i++) {
Set parentSubset = buildCharacterSet(parent.substring(i, i + child.length()));
if (parentSubset.containsAll(children) && children.containsAll(parentSubset)) {
total++;
}
}
return total;
}
static Set buildCharacterSet(String s) {
Set<Character> characterSet = new HashSet<>();
for (int i = 0; i < s.length(); i++) {
characterSet.add(s.charAt(i));
}
return characterSet;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment