diff options
| author | 3gg <3gg@shellblade.net> | 2025-02-05 18:36:31 -0800 |
|---|---|---|
| committer | 3gg <3gg@shellblade.net> | 2025-02-05 18:36:31 -0800 |
| commit | 4689e4e80b479be25f7557d05818f5caa723aafa (patch) | |
| tree | 4df25811fe2a9a15b401375178da6537f4b6063f /top-interview-questions/easy/strings/04_valid_anagram.cc | |
Diffstat (limited to 'top-interview-questions/easy/strings/04_valid_anagram.cc')
| -rw-r--r-- | top-interview-questions/easy/strings/04_valid_anagram.cc | 29 |
1 files changed, 29 insertions, 0 deletions
diff --git a/top-interview-questions/easy/strings/04_valid_anagram.cc b/top-interview-questions/easy/strings/04_valid_anagram.cc new file mode 100644 index 0000000..3ca6b7c --- /dev/null +++ b/top-interview-questions/easy/strings/04_valid_anagram.cc | |||
| @@ -0,0 +1,29 @@ | |||
| 1 | class Solution { | ||
| 2 | public: | ||
| 3 | static void count(const string& s, int* counts) { | ||
| 4 | for (char c : s) { | ||
| 5 | counts[c]++; | ||
| 6 | } | ||
| 7 | } | ||
| 8 | |||
| 9 | bool isAnagram(string s, string t) { | ||
| 10 | if (s.size() != t.size()) { | ||
| 11 | return false; | ||
| 12 | } | ||
| 13 | // strings are equal length | ||
| 14 | |||
| 15 | int sCount[256] = {}; | ||
| 16 | int tCount[256] = {}; | ||
| 17 | |||
| 18 | count(s, sCount); | ||
| 19 | count(t, tCount); | ||
| 20 | |||
| 21 | for (char c : s) { | ||
| 22 | if (sCount[c] != tCount[c]) { | ||
| 23 | return false; | ||
| 24 | } | ||
| 25 | } | ||
| 26 | |||
| 27 | return true; | ||
| 28 | } | ||
| 29 | }; | ||
