Valid Anagram Cont…

Monisha Mathew
1 min readApr 26, 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 2: In the previous post we adopted an approach of using a hashcode created from a 26 element int array. This works great for long Strings with repetitions. But this approach is an overkill for short Strings.

For short Strings simply sorting the characters in the string scan form the hashcode.

Now let’s try a solution that which is based on a combination of these two. The code looks like this —

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

private String getCode(String s){
char[] array = s.toCharArray();
if(array.length>26){
return getLong(array);
}
return getShort(array);
}

private String getShort(char[] array){
Arrays.sort(array);
return String.valueOf(array);
}

private String getLong(char[] array){
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);
}
return str.toString();
}
}

Find more posts here.

Cheers & Chao!

--

--