Site Search:

Valid Anagram

 Problem


Given two strings s and t , write a function to determine if t is an anagram of s.

Example 1:

Input: s = "anagram", t = "nagaram"
Output: true
Example 2:

Input: s = "rat", t = "car"
Output: false
Note:
You may assume the string contains only lowercase alphabets.

Solution

We can compare the frequency of the characters.


import java.util.*;

class Solution {
  public static void main(String[] args) {
    String s = null, t = "";
    System.out.println(solve(s, t));
  }
  private static boolean solve(String s, String t) {
    if(s == null || t == null)
      throw new IllegalArgumentException("bad input");
    char[] freq = new char[26];
    for(char c : s.toCharArray()) {
      freq[c - 'a']++;
    }
    for(char c : t.toCharArray()) {
      freq[c - 'a']--;
      if(freq[c - 'a'] < 0)
        return false;
    }
    for(int i : freq) {
      if(i != 0)
        return false;
    }
    return true;
  }
}

The time complexity is O(max(L1, L2)), space complexity is O(max(L1, L2)), where L1 and L2 is the length of the two strings.