LeetCode Solutions
242. Valid Anagram
Time: $O(n)$ Space: $O(128) = O(1)$
class Solution {
public:
bool isAnagram(string s, string t) {
if (s.length() != t.length())
return false;
vector<int> count(128);
for (const char c : s)
++count[c];
for (const char c : t)
if (--count[c] < 0)
return false;
return true;
}
};
class Solution {
public boolean isAnagram(String s, String t) {
if (s.length() != t.length())
return false;
int[] count = new int[128];
for (final char c : s.toCharArray())
++count[c];
for (final char c : t.toCharArray())
if (--count[c] < 0)
return false;
return true;
}
}
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
dict = Counter(s)
for c in t:
dict[c] -= 1
if dict[c] < 0:
return False
return True