原题如下:
The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...
1
is read off as "one 1"
or 11
.
11
is read off as "two 1s"
or 21
.
21
is read off as "one 2
, then one 1"
or 1211
.
Given an integer n, generate the nth sequence.
Note: The sequence of integers will be represented as a string.
这道题看着挺复杂,但其实还是比较简单的,初始字符串为“1”,然后循环n-1次,每次循环产生一个新的字符串作为下一次循环时的读取的对象,每次从头开始读取字符串前k个相同的字符,将其个数和字符写入新的字符串,并对当前字符串进行截取(去掉已经读取过的字符),直到当前字符串为空串一次循环结束并开始新的循环,最后一次循环结束后得到最终结果。class Solution {
public:
string countAndSay(int n) {
string s = "1";
for(int i = 2; i <= n; i++){
string temp;
while(!s.empty()){
char c = s.front();
int count = 0;
for(int k = 0; k < s.length(); k++){
if(s[k] != c)
break;
count++;
}
char cCount = count + '0';
temp.append(1,cCount);
temp.append(1,c);
s = s.substr(count);
}
s = temp;
}
return s;
}
};
这道题的重点是掌握对字符串的截取及追加等操作,以及字符数字之间的转换。