Created
August 8, 2018 05:50
-
-
Save deyindra/5f12024f4bd97c670efb412c99d316ce to your computer and use it in GitHub Desktop.
Group Anagram (Prime Hash)
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.util.*; | |
public class Anagrams { | |
private static int[] primeTables; | |
private static void populatePrimeTable(){ | |
if(primeTables==null){ | |
primeTables = new int[128]; | |
PrimeNumber primeNumber = new PrimeNumber(10000); | |
int j=0; | |
for(int i=0;i<=10000;i++){ | |
if(primeNumber.isPrime(i) && j<primeTables.length){ | |
primeTables[j]=i; | |
j++; | |
} | |
} | |
} | |
} | |
private static long generatePrimeHash(String str){ | |
assert (str!=null && str.trim().length()>0); | |
char[] array = str.toCharArray(); | |
long hash=1; | |
for(char ch:array){ | |
int index=(int)ch; | |
hash = hash*primeTables[index]; | |
} | |
return hash; | |
} | |
public Collection<List<String>> groupAnagrams(List<String> list){ | |
populatePrimeTable(); | |
Map<Long, List<String>> map=null; | |
if(list!=null && !list.isEmpty()){ | |
map = new HashMap<>(); | |
for(String str:list){ | |
long prime = generatePrimeHash(str); | |
List<String> subList = map.get(prime); | |
if(subList==null){ | |
subList = new ArrayList<>(); | |
} | |
subList.add(str); | |
map.put(prime,subList); | |
} | |
return map.values(); | |
}else{ | |
return null; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment