java - Anagrams lintcode -
given array of strings, return groups of strings anagrams.
given ["lint", "intl", "inlt", "code"], return ["lint", "inlt", "intl"].
given ["ab", "ba", "cd", "dc", "e"], return ["ab", "ba", "cd", "dc"].
my code gave error msg @ "stringb.add(astring));"
; couldn4t figure out why.
{ /** * @param strs: list of strings * @return: list of strings */ private int hash(int[] count){ int hash = 0; int primea = 378551; int primeb = 378559; //int result = 0; for(int anumber: count){ hash = hash*primea + anumber; primea = primea*primeb; } } public list<string> anagrams(string[] strs) { // write code here int = 0; int l = 0; arraylist<string> result = new arraylist<string>(); map<integer, arraylist<string>> strings = new hashmap<integer, arraylist<string>>(); for(string astring : strs){ int[] charcount = new int[26]; for(i = 0; i<astring.length(); i++){ charcount[astring.charat[i]-'a']++; } l = hash(charcount); if(!strings.containskey(l)){ strings.put(l,new arraylist<string>()); } arraylist<string> stringb = strings.get(l); stringb.add(astring)); } for(arraylist<string> alist: strings.values()){ if(alist.size()>1){ result.addall(alist); } } result result; } }
Comments
Post a Comment