242. Valid Anagram

1 min read
Table of contents
[EASY] Link: https://leetcode.com/problems/valid-anagram/description/
Description: Given two strings s
and t
, return true
if t
is an anagram of s
, and false
otherwise.
Example 1:
Input: s = “listen” , t = “silent” & s = “heart”, t = “earth” …
Output: True
Example 2:
Input: s = “hat”, t = “hit”
Output: False
1. Sort
class Solution {
public:
bool isAnagram(string s, string t) {
sort(s.begin(), s.end());
sort(t.begin(), t.end());
for (int i = 0; i < max(s.size(), t.size()); i++)
{
if (t[i] != s[i]) return false;
}
return true;
}
};
2. Hash Map
class Solution {
public:
bool isAnagram(string s, string t) {
if (s.size() != t.size()) return false;
unordered_map <char,int> countS, countT;
for (int i = 0; i < t.size(); i++)
{
countT[t[i]]++;
countS[s[i]]++;
}
return countT == countS;
}
};
0
Subscribe to my newsletter
Read articles from Duong Thi Kim Ngan directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by