Created
May 22, 2015 17:57
-
-
Save calebastey/3de9d819a2f087866e3d to your computer and use it in GitHub Desktop.
Anagram.java
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.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