public static Map<String, Integer> primeMap() {
List<Integer> list = getPrime(26);
Map<String, Integer> map = new HashMap<String, Integer>();
char ch = 'a';
for(Integer p : list) {
map.put(ch + "", p);
ch += 1;
}
return map;
}
public static Integer getProduct(String str) {
Map<String, Integer> map = primeMap();
int p = 1;
for(int i=0; i<str.length(); i++) {
p *= map.get((str.charAt(i) + "").toLowerCase());
}
return p;
}
public static List<String> anagrams(List<String> list, String str) {
Map<Integer, List<String> > map = new HashMap<Integer, List<String>>();
for(String s : list) {
List<String> l = map.get(getProduct(s));
if(l != null) {
l.add(s);
map.put(getProduct(s), l);
} else {
List<String> ll = new ArrayList<String>();
ll.add(s);
map.put(getProduct(s), ll);
}
}
return map.get(getProduct(str));
}
public static List<Integer> intersection(List<List<Integer>> lists) {
List<Integer> retList = new ArrayList<Integer>();
if(lists != null) {
Map<Integer, Set<Integer>> map = new HashMap<Integer, Set<Integer>>();
for (int i = 0; i < lists.size(); i++) {
List<Integer> list = lists.get(i);
for (Integer n : list) {
Set<Integer> set = map.get(n);
if (set != null) {
set.add(i);
map.put(n, set);
} else {
Set<Integer> nSet = new HashSet<Integer>();
nSet.add(i);
map.put(n, nSet);
}
}
}
for (Map.Entry<Integer, Set<Integer>> entry : map.entrySet()) {
Integer n = entry.getKey();
Set<Integer> set = map.get(n);
if (set.size() == lists.size())
retList.add(n);
}
}
return retList;
}
//================================================================================
// java anagram
// Use sort technic to solve anagrams problem
// Use sorted str as key
// {dog, god}
// dgo->{dog, god}
// --------------------------------------------------------------------------------
static String sortStr(String s) {
char[] clist = s.toCharArray();
Arrays.sort(clist);
return String.valueOf(clist);
}
static List<String> anagrams(List<String> list, String input) {
Map<String, List<String>> map = new HashMap<String, List<String>>();
if(list != null && input != null) {
for(String str : list) {
String key = sortStr(str);
List<String> l = map.get(key);
if(l != null) {
l.add(str);
map.put(key, l);
} else {
List<String> ll = new ArrayList<String>();
ll.add(str);
map.put(key, ll);
}
}
}
return map.get(sortStr(input));
}