Example: Valid Anagram - rFronteddu/general_wiki GitHub Wiki

Given two strings s and t of lower case letters, return true if t is an anagram of s, and false otherwise.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Solution

To determine if one string is an anagram of another, we need to check if both strings contain the same characters with the same frequencies.

Approach:

  • Check Lengths: If the lengths of the two strings are not equal, they cannot be anagrams.
  • Count Characters: Use an array to count the occurrences of each character in both strings.
  • Compare Counts: If the character counts match for both strings, they are anagrams.
public class Solution {
    public boolean isAnagram(String s, String t) {
        if (s.length() != t.length()) {
            return false;
        }

        // Create a count array for 26 lowercase English letters
        int[] count = new int[26];

        // Count characters in s
        for (int i = 0; i < s.length(); i++) {
            count[s.charAt(i) - 'a']++;
        }

        // Decrement count for characters in t
        for (int i = 0; i < t.length(); i++) {
            count[t.charAt(i) - 'a']--;
        }

        // Check if all counts are zero
        for (int i = 0; i < 26; i++) {
            if (count[i] != 0) {
                return false;
            }
        }

        return true;
    }
}