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.
Count character frequencies and compare.
sts = "anagram", t = "nagaram"
Frequency map of s:
a: 3, n: 1, g: 1, r: 1, m: 1
Check t:
n: 3->2, a: 1->0, g: 1->0, a: 0->-1...
Wait, process correctly:
All frequencies match! Return true
Sort both strings and compare.
1/**
2 * Valid Anagram
3 * Time: O(n), Space: O(1)
4 */
5
6import java.util.*;
7
8class Solution {
9 public boolean isAnagram(String s, String t) {
10 if (s.length() != t.length()) {
11 return false;
12 }
13
14 int[] count = new int[26];
15
16 for (int i = 0; i < s.length(); i++) {
17 count[s.charAt(i) - 'a']++;
18 count[t.charAt(i) - 'a']--;
19 }
20
21 for (int c : count) {
22 if (c != 0) return false;
23 }
24
25 return true;
26 }
27}
28
29// Sorting approach
30class Solution2 {
31 public boolean isAnagram(String s, String t) {
32 if (s.length() != t.length()) {
33 return false;
34 }
35
36 char[] sChars = s.toCharArray();
37 char[] tChars = t.toCharArray();
38 Arrays.sort(sChars);
39 Arrays.sort(tChars);
40
41 return Arrays.equals(sChars, tChars);
42 }
43}
44