Pergunta de entrevista da empresa Amazon

find a anagrams of given string from the paragraph.

Respostas da entrevista

Sigiloso

21 de out. de 2012

First find all permutations of given String store in hashset. Go word by word in paragraph, first check if word has same length as given String and if successful then check if word is in hashset or not. If present then print it.

2

Sigiloso

25 de out. de 2012

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; }

Sigiloso

13 de jun. de 2012

used a hashing method. try to find it in the book "data structure and algorithm using java"