Valid Anagram 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:
Input: s = "anagram", t = "nagaram" Output: true
Example 2:
Input: s = "rat", t = "car" Output: false
Constraints:
1 <= s.length, t.length <= 5 * 104
s
andt
consist of lowercase English letters.
Valid Anagram Solutions
✅Time: O(n)
✅Space: O(128)=O(1)
C++
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;
}
};
Java
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;
}
}
Python
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
Watch Tutorial
Checkout more Solutions here