diff options
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 | }; | ||