2026-06-01 18:12:40 +08:00
|
|
|
#+ANKI_DECK: study_deck_02
|
|
|
|
|
* DONE 0242. Valid Anagram :easy:
|
2026-06-01 02:33:30 +08:00
|
|
|
:PROPERTIES:
|
2026-06-01 17:22:07 +08:00
|
|
|
:NEETCODE: [[file:../../roadmap.org::*0242. Valid Anagram][0242. Valid Anagram]]
|
2026-06-01 02:33:30 +08:00
|
|
|
:END:
|
|
|
|
|
|
2026-06-01 17:22:07 +08:00
|
|
|
Given two strings ~s~ and ~t~, return ~true~ if ~t~ is an anagram of ~s~, and ~false~ otherwise.
|
|
|
|
|
|
|
|
|
|
*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 * 10^{4}~
|
|
|
|
|
|
|
|
|
|
- ~s~ and ~t~ consist of lowercase English letters.
|
|
|
|
|
|
|
|
|
|
*Follow up:* What if the inputs contain Unicode characters? How would you adapt your solution to such a case?
|
|
|
|
|
|
2026-06-01 18:12:40 +08:00
|
|
|
** DONE Approach
|
2026-06-01 02:39:53 +08:00
|
|
|
Write your approach here.
|
|
|
|
|
|
2026-06-01 18:12:40 +08:00
|
|
|
** DONE Python
|
2026-06-05 22:32:49 +08:00
|
|
|
#+begin_src python :lc-problem 242 :lc-lang python3
|
2026-06-01 17:22:07 +08:00
|
|
|
class Solution:
|
|
|
|
|
def isAnagram(self, s: str, t: str) -> bool:
|
2026-06-01 02:39:53 +08:00
|
|
|
#+end_src
|
|
|
|
|
|
2026-06-01 18:12:40 +08:00
|
|
|
** DONE C++
|
2026-06-05 22:32:49 +08:00
|
|
|
#+begin_src cpp :lc-problem 242
|
2026-06-01 18:12:40 +08:00
|
|
|
#include <map>
|
|
|
|
|
#include <string>
|
2026-06-01 17:22:07 +08:00
|
|
|
class Solution {
|
|
|
|
|
public:
|
2026-06-01 18:12:40 +08:00
|
|
|
bool isAnagram(std::string s, std::string t) {
|
|
|
|
|
std::map<char, int> ctr;
|
|
|
|
|
for (char c: s) {
|
|
|
|
|
ctr[c] += c;
|
2026-06-01 17:22:07 +08:00
|
|
|
}
|
2026-06-01 18:12:40 +08:00
|
|
|
for (char c: t) {
|
|
|
|
|
if (ctr[c] == 0) {
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
ctr[c] -= 1;
|
|
|
|
|
if (ctr[c] == 0) {
|
|
|
|
|
ctr.erase(c);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return ctr.size() == 0;
|
|
|
|
|
}
|
2026-06-01 17:22:07 +08:00
|
|
|
};
|
2026-06-01 02:33:30 +08:00
|
|
|
#+end_src
|