-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompareString.cpp
More file actions
80 lines (74 loc) · 1.79 KB
/
Copy pathcompareString.cpp
File metadata and controls
80 lines (74 loc) · 1.79 KB
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include <iostream>
#include <string>
#include <unordered_map>
#define method1 0
#define method2 0
#define method3 1
class Soluction
{
public:
#if method1
//时间复杂度为O(n),空间复杂度为O(1)
bool compareString(std::string &A, std::string &B)
{
int count[26] = {0};
for(int i = 0; i < A.size(); ++i)
count[A[i] - 'A']++;
for(int i = 0; i < A.size(); ++i)
count[B[i] - 'A']--;
for(int i = 0; i < 26; ++i)
{
if(count[i] < 0)
return false;
}
return true;
}
#endif
#if method2
//时间复杂度为O(n),空间复杂度为O(1)
bool compareString(std::string &A, std::string &B)
{
if(A.size() < B.size())
return false;
int letter[26] = {0};
for(int i = 0; i < A.size(); ++i)
letter[A[i] - 'A']++;
for(int i = 0; i < B.size(); ++i)
{
if(letter[B[i] - 'A'] <= 0)
return false;
else
letter[B[i] - 'A']--;
}
return true;
}
#endif
#if method3
//时间复杂度为O(1), 空间复杂度为O(n)
bool compareString(std::string &A, std::string &B)
{
std::unordered_map<char, int> table;
for(int i = 0; i < A.size(); ++i)
table[A[i]]++;
for(int i = 0; i < B.size(); ++i)
{
if(table.find(B[i]) != table.end() && table[B[i]] > 0)
table[B[i]]--;
else
return false;
}
return true;
}
#endif
};
int main()
{
Soluction s;
std::string str = "ABC";
std::string str2 = "AC";
if(s.compareString(str, str2))
std::cout << "True\n" << std::endl;
else
std::cout << "False\n" << std::endl;
return 0;
}