Count And Say

Count And Say

题目描述:

给定一个数字n,找到按照如下规律的第n个字符串。
1: 11 即1个1
2: 21 即2个1
3: 1211 即1个2两个1
4: 111221 即1个1,1个2,2个1

例子:

具体描述看LeetCode38

解题思路:

通过观察规律我们知道,我们需要定义一个函数,输入为上一轮的结果,输出为当前轮的结果。然后将当前轮的结果作为下一轮的输入不断循环即可。

代码如下:

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
class Solution {
public:
string countAndSay(int n) {
string start = to_string(1);
if (n == 1) return start;
string result;
while(n > 1){
result = helper(start);
//得到当前轮的结果
start = result;
//将结果作为下一轮的输入
n--;
}
return result;
}
string helper(string s){
//用来产生下一轮的字符串
string res;
int index = 0;
while(index < s.size()){
int count = 1;
while(index + 1 < s.size() && s[index + 1] == s[index]){
index++;
count++;
}
//这个循环找到有多少个相同的字符
string tmp = to_string(count) + s[index];
index++;
res += tmp;
//将字符串连接
}
return res;
}
};