题目描述
The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...
1is read off as"one 1"or11.
11is read off as"two 1s"or21.
21is read off as"one 2, thenone 1"or1211.
Given an integer n, generate the nth sequence.
Note: The sequence of integers will be represented as a string.
---------------------------------------
注意题目是求整个序列的第N项,而每一项是其前一项的解释!!!
1
class Solution {
2
public:
3
string countAndSay(int n) {
4
//题意:求序列的第n项(每一项是其前一项的‘解释’)
5
string res("1");//第一项
6
7
if (n==1)
8
return res;
9
for (int i=2; i<=n; ++i){
10
int len = res.size();
11
int count = 1;
12
string temp="";//用于运行中暂存当前项结果
13
for (int j=0; j<len; ++j){
14
if (j!=len-1){
15
if (res[j] ==res[j+1]){
16
count++;
17
}
18
else {
19
20
temp += to_string(count);
21
temp += res[j];
22
count = 1;
23
}
24
}else {
25
26
temp += to_string(count);
27
temp += res[j];
28
}
29
}
30
res = temp;//更新当前项结果
31
}
32
return res;
33
}
34
};
您的代码已保存