Java String Anagrams

Problem
Two strings and are called anagrams if they consist same characters, but may be in different orders. So the list of anagrams of is .

Given two strings, print Anagrams if they are anagrams, print Not Anagrams if they are not. The strings may consist at most English characters; the comparison should NOT be case sensitive.

This exercise will verify that you can sort the characters of a string, or compare frequencies of characters.

Sample Input 0

anagram
margana

Sample Output 0

Anagrams

Sample Input 1

anagramm
marganaa
Sample Output 1:

Not Anagrams

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
    /**
     * Two strings and are called anagrams if they consist same characters, but may be in different orders. So
     * the list of anagrams of is .
     *
     * Given two strings, print Anagrams if they are anagrams, print Not Anagrams if they are not. The strings
     * may consist at most English characters; the comparison should NOT be case sensitive.
     *
     * This exercise will verify that you can sort the characters of a string, or compare frequencies of
     * characters.
     *
     * @param a
     * @param b
     *
     * @return
     */

    static boolean isAnagram( String a, String b ) {

        Collection<String> s1 = new ArrayList<>();

        for (int i = 0; i < a.length(); i++) {
            s1.add( String.valueOf( a.charAt( i ) ).toUpperCase() );
        }

        boolean result = true;
        for (int i = 0; i < b.length(); i++) {
            String charAt = String.valueOf( b.charAt( i ) ).toUpperCase();
            if ( !s1.contains( charAt ) ) {
                result = false;
            } else {
                s1.remove( charAt );
                //System.out.print( charAt + " : " );
                //System.out.println( s1 );
            }
        }

        return s1.size() > 0 ? false : result;
    }
Tagged , , , . Bookmark the permalink.

Leave a Reply