Posts Anagram (geeksforgeeks - SDE Sheet)
Post
Cancel

Anagram (geeksforgeeks - SDE Sheet)

PROBLEM DESCRIPTION

Given two strings a and b consisting of lowercase characters. The task is to check whether two given strings are an anagram of each other or not. An anagram of a string is another string that contains the same characters, only the order of characters can be different. For example, act and tac are an anagram of each other. Strings a and b can only contain lower case alphabets.

geeksforgeeks

SOLUTION

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
class Solution {

    // Function is to check whether two strings are anagram of each other or not.
    public static boolean isAnagram(String a, String b) {

        int n = a.length();

        if(b.length() != n)
            return false;

        int[] f = new int[26];

        for(int i=0; i<n; i++){
            f[a.charAt(i)-'a']++;
            f[b.charAt(i)-'a']--;
        }

        for(int i=0; i<26; i++){
            if(f[i] != 0)
                return false;
        }

        return true;

    }

}
This post is licensed under CC BY 4.0 by the author.