Valid Anagram

Monisha Mathew
1 min readApr 25, 2019

--

Question: 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

You may view the full question here.

Approach 1: Here is an approach inspired by the popular solution posted on leetcode. Let’s try building a custom HashCode such that all anagrams can be represented by the same value. Let’s see how the code looks like —

//Approach 1:
//Runtime: 3ms
//Memory usage: 37.7MB
class Solution {
public boolean isAnagram(String s, String t) {
return getCode(s).equals(getCode(t));
}

private String getCode(String s){
char[] array = s.toCharArray();
int[] i = new int[26];
for(char c : array){
i[c-'a'] = i[c-'a']+1;
}
StringBuilder str = new StringBuilder("");
for(int j : i){
str.append(j)
.append("#");
}
return str.toString();
}
}

Check out this post for an improved solution.

Find more posts here.

Cheers & Chao!

--

--