forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main2.cpp
41 lines (30 loc) · 853 Bytes
/
main2.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/// Source : https://leetcode.com/problems/valid-anagram/
/// Author : liuyubobobo
/// Time : 2017-01-17
#include <iostream>
using namespace std;
/// Using Hashtable
/// Time Complexity: O(n)
/// Space Complexity: O(26)
class Solution {
public:
bool isAnagram(string s, string t) {
if( s.size() != t.size() )
return false;
int freq[26] = {0};
for( int i = 0 ; i < s.size() ; i ++ )
freq[s[i]-'a'] ++;
for( int i = 0 ; i < t.size() ; i ++ ){
freq[t[i]-'a'] --;
if( freq[t[i]-'a'] < 0 )
return false;
}
return true;
}
};
int main() {
cout << Solution().isAnagram("anagram", "nagaram") << endl;
cout << Solution().isAnagram("rat", "car") << endl;
cout << Solution().isAnagram("ab", "a") << endl;
return 0;
}