-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path38.cpp
More file actions
38 lines (34 loc) · 826 Bytes
/
38.cpp
File metadata and controls
38 lines (34 loc) · 826 Bytes
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
// Author: btjanaka (Bryon Tjanaka)
// Problem: (Leetcode) 38
// Title: Count and Say
// Link: https://leetcode.com/problems/count-and-say
// Idea: Repeatedly apply the rule to generate the next string.
// Difficulty: easy
// Tags: implementation
class Solution {
public:
string generateSay(const string& cur) {
string res;
int i = 0;
int count;
while (i < cur.size()) {
count = 1;
++i; // Make sure that we move forward at least 1
while (i < cur.size() && cur[i] == cur[i - 1]) {
++i;
++count;
}
res.push_back(count + '0');
res.push_back(cur[i - 1]);
}
return res;
}
string countAndSay(int n) {
if (n <= 0) return "";
string res = "1";
for (int i = 1; i < n; ++i) {
res = generateSay(res);
}
return res;
}
};