public class MiscDemo {
public static void main(String[] args) { String []input = {"cat","good","tac","act","odog"}; MiscDemo misc = new MiscDemo(); misc.segragateAnagram(input); System.out.println(); } public void segragateAnagram(String input[]){ Map<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>(); Set<String> keys = map.keySet(); String word; for(int i=0; i<input.length;i++){ if(this.matchingAnagramKey(keys, input[i])!=null){ word = this.matchingAnagramKey(keys, input[i]); map.get(word).add(input[i]); }else{ map.put(input[i], new ArrayList<String>()); } } System.out.println(map.get("cat").size()); } public String matchingAnagramKey(Set<String> keys, String b){ for(String word:keys){ if(isAnagram(word, b)){ return word; }else{ } } return null; } public boolean isAnagram(String a, String b){ // Their length shoud be same \ // Their both String contain same character and same number of character but there order might be diifer. int m = a.length(); int n = a.length(); if(m!=n){ return false; } int []count1 = new int[26]; int []count2 = new int[26]; // using single count array for(int i=0;i<n;i++){ count1[a.charAt(i)-97]+=1; } for(int i=0;i<n;i++){ count1[b.charAt(i)-97]-=1; } for(int i=0;i<26;i++){ if(count1[i]!=0){ return false; } } return true; } } |