Leetcode 38. Count and Say

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Count and Say

2. Solution

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
class Solution {
public:
string countAndSay(int n) {
if(n == 1) {
return "1";
}
string result;
string current = "1";
for(int i = 1; i < n; i++) {
result = statistic(current);
current = result;
}
return result;
}

private:
string statistic(string s) {
string result;
int count = 1;
char current = s[0];
for(int i = 1; i < s.length(); i++) {
if(current == s[i]) {
count++;
}
else {
result = result + to_string(count) + current;
current = s[i];
count = 1;
}
}
return result + to_string(count) + current;
}
};

Reference

  1. https://leetcode.com/problems/count-and-say/description/
如果有收获,可以请我喝杯咖啡!