Pacific-Design.com

    
Home Index

1. Algorithms

2. Anagram

Algorithms / Anagram /

Anagram - O (n log n)

  1. Lower Case
  2. Sort
  3. Compare
public static boolean isAnagram(String str1, String str2){

        str1 = str1.toLowerCase();
        str2 = str2.toLowerCase();

        char[] ch1 = str1.toCharArray();
        char[] ch2 = str2.toCharArray();

        Arrays.sort(ch1);
        Arrays.sort(ch2);

        String str3 = new String(ch1);
        String str4 = new String(ch2);

        return str3.equals(str4);
}

Find Anagram

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
public class Anagram {

    public findAnagram(List<String> names) {
        
        Map<String, String> map = new HashMap();
      
        for(int i=0; names.length(); i++) {
            String sorted = names.get(i);
            Arrays.sort(sorted);
        
            String temp = map.get(sorted);
            if(temp) {
                map.put(sorted, temp + "|" + names.get(i)); 
            } else { 
                map.put(sorted, names.get(i));
            }        
        }
      
        for(Map.Entry<String,String> entery : map.entrySet()) {
        
            String key = entry.getKey();
            String values = entry.getValue();
        
            if(values.indexOf('|')) {
                System.out.println("Anagram" + key + " Words=" + values); 
            }        
        }    
    }
  
    public static void main(String[] args) {
        List<String> names = new ArrayList<>();
        names.add("act");
        names.add("bat");
        names.add("cat");        
        names.add("tab");
        names.add("tac");        
        names.add("kevin");        
        
        findAnagram(names);
    }          
}