-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path38.cpp
More file actions
66 lines (58 loc) · 1.38 KB
/
38.cpp
File metadata and controls
66 lines (58 loc) · 1.38 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
class Solution {
public:
string countAndSay(int n) {
if(n==0)
return "";
if(n==1)
return "1";
n--;
string num = "1";
while(n--){
int j = 0;
int count = 0;
string res = "";
while(j<num.size()){
count = 1;
while(j<num.size()-1 && num[j]==num[j+1]){
j++;
count++;
}
res += to_string(count) + num[j];
j++;
}
num = res;
}
return num;
}
};
class Solution {
public:
string countAndSayNext(const string& current) {
stringstream ss;
int count = -1;
char last_char;
for(char c : current) {
if(count == -1) {
last_char = c;
count = 1;
continue;
}
if(c == last_char) {
count++;
continue;
}
ss << count << last_char;
last_char = c;
count = 1;
}
ss << count << last_char;
return ss.str();
}
string countAndSay(int n) {
string result = "1";
for(int i = 1; i < n; ++i) {
result = countAndSayNext(result);
}
return result;
}
};