Given two strings s
and t
, 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.
LeetCode Problem - 242
class Solution {
// Method to check if two strings are anagrams of each other
public boolean isAnagram(String s, String t) {
// If the lengths of the strings are different, they cannot be anagrams
if (s.length() != t.length()) return false;
// Initializing an array to count occurrences of each character
int[] count = new int[26];
// Counting occurrences of characters in string s
for (char c : s.toCharArray()) {
count[c - 'a']++;
}
// Checking occurrences of characters in string t and decrementing counts
for (char c : t.toCharArray()) {
int idx = c - 'a';
count[idx]--;
// Early termination if count becomes negative, indicating an excess character
if (count[idx] < 0) return false;
}
// If all characters are accounted for, return true (strings are anagrams)
return true;
}
}