Sorting
Intuition
If two strings are anagrams, sorting them will produce the same string. We can sort both strings and compare them directly. If the sorted versions are equal, the strings are anagrams. This is simple to implement but sorting dominates the time complexity.
Algorithm
- If the lengths of s and t differ, return false immediately.
- Sort both strings.
- Compare the sorted strings. If they are equal, return true; otherwise return false.
O(n log n)SpaceO(n)Code (C++ · Java · Python · Go)
class Solution {
public:
bool isAnagram(string s, string t) {
if (s.length() != t.length()) return false;
sort(s.begin(), s.end());
sort(t.begin(), t.end());
return s == t;
}
};class Solution {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) return false;
char[] sArr = s.toCharArray();
char[] tArr = t.toCharArray();
Arrays.sort(sArr);
Arrays.sort(tArr);
return Arrays.equals(sArr, tArr);
}
}def isAnagram(s: str, t: str) -> bool:
if len(s) != len(t):
return False
return sorted(s) == sorted(t)import "sort"
func isAnagram(s string, t string) bool {
if len(s) != len(t) {
return false
}
sBytes := []byte(s)
tBytes := []byte(t)
sort.Slice(sBytes, func(i, j int) bool { return sBytes[i] < sBytes[j] })
sort.Slice(tBytes, func(i, j int) bool { return tBytes[i] < tBytes[j] })
return string(sBytes) == string(tBytes)
}