Valid Anagram

Valid Anagram

Coding Solution

·

1 min read

Problem

Given two strings, return true if one of them is an anagram of another. This is similar to the Leetcode Problem - Valid Anagram

Approach

The approach would be creating a character array containing 26 alphabets as characters. We then iterate both strings, add characters from one of the strings and remove them using another string at the same index. If the count of each character is equal to 0, it is a valid anagram.

class Solution {
    public boolean isAnagram(String s, String t) {
         if(s.length()!=t.length()){
            return false;
        }
        int[] count = new int[26];
        for(int i=0;i<s.length();i++){
            count[s.charAt(i)-'a']++;
            count[t.charAt(i)-'a']--;
        }
        for(int i:count){
            if(i!=0){
                return false;
            }
        }
        return true;
    }
}

Do have a look at the discuss section for more optimized solutions if available - LeetCode Discuss