-
Notifications
You must be signed in to change notification settings - Fork 0
/
Count and Say.cpp
74 lines (65 loc) · 1.68 KB
/
Count and Say.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
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
// https://oj.leetcode.com/problems/count-and-say/
// iteration
class Solution {
public:
string countAndSay(int n) {
if (n < 0) {
return "";
}
if (n == 1) {
return "1";
}
string last = "1";
string cur = "";
for (int i = 2; i <= n; i++) {
string cur;
char last_c = last[0];
int cnt = 1;
for (int j = 1; j < last.size(); j++) {
if (last[j] == last_c) {
cnt++;
} else {
cur += to_string(cnt);
cur += last_c;
cnt = 1;
last_c = last[j];
}
}
cur += to_string(cnt);
cur += last_c;
last.assign(cur);
cur = "";
}
return last;
}
};
// recursion
class Solution {
public:
string countAndSay(int n) {
if (n <= 0) {
return "";
}
if (n == 1) {
return "1";
}
string last = countAndSay(n - 1);
string next = "";
size_t last_size = last.size();
char cur_digit = last[0];
int cur_count = 0;
for (size_t i = 0; i < last_size; i++) {
if (last[i] == cur_digit) {
cur_count++;
} else {
next += to_string(cur_count);
next += cur_digit;
cur_digit = last[i];
cur_count = 1;
}
}
next += to_string(cur_count);
next += cur_digit;
return next;
}
};