LeetCode 242: Valid Anagram
Problem Description
Explanation
To solve this problem, we can first check if the lengths of the two strings are different. If they are not, we can create a frequency map for each character in both strings. Then, we compare the frequency maps to check if they are equal. If they are equal, it means the two strings are anagrams of each other.
Algorithm:
- Check if the lengths of strings
s
andt
are different. If they are, return false. - Create frequency maps for characters in strings
s
andt
. - Compare the frequency maps. If they are equal, return true; otherwise, return false.
Time Complexity
The time complexity of this solution is O(n), where n is the length of the input strings s
and t
.
Space Complexity
The space complexity of this solution is O(1) because we are using a fixed-size array to store the frequency of characters.
Solutions
class Solution {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) {
return false;
}
int[] count = new int[26];
for (char c : s.toCharArray()) {
count[c - 'a']++;
}
for (char c : t.toCharArray()) {
count[c - 'a']--;
}
for (int i = 0; i < 26; i++) {
if (count[i] != 0) {
return false;
}
}
return true;
}
}
Related LeetCode Problems
Loading editor...