Table of contents
Open Table of contents
The Problem
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.
| Example 1 | Example 2 |
|---|---|
Input: s = “anagram”, t = “nagaram”Output: true | Input: s = “rat”, t = “car”Output: false |
The Approach
The goal is to ensure that the lengths of the two strings are equal & they each contain the same letters with the same frequency.
As such, we first check that the lengths are equal. Once this condition is satisfied, sort the strings using Arrays.sort().
If the two strings are anagrams of each other, sorting them will return the same string. We then check for this condition with Arrays.equals(), returning the outcome.
My Solution
class Solution {
public boolean isAnagram(String s, String t) {
// Checks if the lengths are equal.
if (!(s.length() == t.length())) {
return false;
}
// Converted to char Array, sorted & checked if they are equal.
char[] array1 = s.toCharArray();
char[] array2 = t.toCharArray();
Arrays.sort(array1);
Arrays.sort(array2);
return Arrays.equals(array1, array2);
}
}
Firstly, we check that the two strings have the same length.
The two strings are converted to a char array to utilize the methods of the Arrays class.
They are then sorted using Arrays.sort(). If the two sorted arrays are equal (i.e. valid anagrams), then Arrays.equals(array1, array2) will return true.
An alternative solution written in C.
// Comparator for chars.
int characterComparator(char* a, char* b) {
return ((int) *a) - ((int) *b);
}
// Sorts both strings & checks for equality.
bool isAnagram(char* s, char* t) {
int sLength = strlen(s);
int tLength = strlen(t);
if (sLength != tLength) {
return false;
}
qsort(s, sLength, sizeof(char), characterComparator);
qsort(t, tLength, sizeof(char), characterComparator);
int outcome = strcmp(s, t);
if (outcome == 0) {
return true;
} else {
return false;
}
}
</details>