public String findAnagram(String string, String paragraph){
///////// invalid forms checking ie: null or string.length > paragraph.legth //////////////
HastMap stringCharCounter = counterCharacter(string);
String[] array = paragraph.split(" "); // assuming that the paragraph consist of English characters only
// also assuming that there is only one white space character in between two words.
// otherwise cleaning up function may required
for(String s : array){
HashMap tmpMap = countCharacter(s);
if(compareHashMap(stringCharCounter,tmpMap)){
return s;
}
}
return null;
}
private HashMap countCharacter(String s){
////// invalid forms checking /////
HashMap map = new HashMap();
for(char c : s.toCharArray()){
Integer val;
if((val = map.get(c)) != null){
map.put(c, val + 1);
} else {
map.put(c, 0);
}
}
return map;
}
private boolean compareHashMap(HashMap mapOne, HashMap mapTwo) {
////// invalid forms checking /////
if(mapOne.size() != mapTwo.size()){
return false;
}
// we only need to check one time b/c we know that the maps are in the same size
// Therefore , if there is a key that is not in both map the comparison will return false;
for( Entryc : mapOne.entrySet()){
int valOne = c.getValue().intValue();
int valTwo = mapTwo.get( c.charValue() ).intValue();
if( valOne != valTwo ){
return false;
}
}
return true;
}