Valid Anagram

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


Example 1:


Input: s = "anagram", t = "nagaram"


Output: true


Example 2:


Input: s = "rat", t = "car"


Output: false


 class Solution {

    public boolean isAnagram(String s, String t) {
       
  if(s.length() !=t.length())
  {
    return false;
  }
Map<Character, Integer> freq = new HashMap<>();

for(char c:s.toCharArray())
{

freq.put(c,freq.getOrDefault(c,0)+1);
}
for(char ch:t.toCharArray())
{

freq.put(ch,freq.getOrDefault(ch,0)-1);
}

     for (int count : freq.values()) {
            if (count != 0) return false;
        }
return true;


    }
}

Comments

Popular posts from this blog

Two Sum II - Input Array Is Sorted

Comparable Vs. Comparator in Java

Increasing Triplet Subsequence