-
Notifications
You must be signed in to change notification settings - Fork 0
/
191209-1.cpp
46 lines (44 loc) · 865 Bytes
/
191209-1.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
// https://leetcode-cn.com/problems/count-and-say/
#include <cstdio>
#include <string>
using namespace std;
class Solution {
public:
string countAndSay(int n) {
if (n <= 1) {
return "1";
} else {
string s = countAndSay(n - 1);
string r;
char c = 0;
char n = '0';
for (const char* p = s.c_str(); *p; ++p) {
if (*p != c) {
if (n > '0') {
r += n;
r += c;
}
c = *p;
n = '1';
} else {
++n;
}
}
if (n > '0') {
r += n;
r += c;
}
return r;
}
}
};
int main()
{
Solution s;
printf("%s\n", s.countAndSay(1).c_str()); // answer: 1
printf("%s\n", s.countAndSay(2).c_str()); // answer: 11
printf("%s\n", s.countAndSay(3).c_str()); // answer: 21
printf("%s\n", s.countAndSay(4).c_str()); // answer: 1211
printf("%s\n", s.countAndSay(5).c_str()); // answer: 111221
return 0;
}