-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathp038.cpp
49 lines (49 loc) · 1.44 KB
/
p038.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
42
43
44
45
46
47
48
49
class Solution {
public:
string countAndSay(int n) {
if (n == 1) return "1";
vector<pair<int, int>> v[2];
v[0].push_back(pair<int, int>(1, 1));
int i, j;
for (i = 3; i <= n; i++)
{
vector<pair<int, int>> *dst = &v[i&1], *src = &v[(i+1)&1];
dst->clear();
int val = (*src)[0].first;
int cnt = 0;
for (j = 0; j < src->size(); j++)
{
if (val == (*src)[j].first)
{
cnt++;
}
else
{
dst->push_back(pair<int, int>(cnt, val));
val = (*src)[j].first;
cnt = 1;
}
if (val == (*src)[j].second)
{
cnt++;
}
else
{
dst->push_back(pair<int, int>(cnt, val));
val = (*src)[j].second;
cnt = 1;
}
}
dst->push_back(pair<int, int>(cnt, val));
}
int len = v[n&1].size()*2;
char *result = new char[len+1];
result[len] = '\0';
for (i = 0; i < len>>1; i++)
{
result[(i<<1)] = v[n&1][i].first+'0';
result[(i<<1)+1] = v[n&1][i].second+'0';
}
return result;
}
};