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.
题目解析:
其实题目很简单,就是计算个数,并填充到新的数组中。由于对C++不熟悉,如何给string加上一个字符还不太懂,不过参考了别人的总算写出来了,但其中机理还是不明白。string类型,除了可以直接加字符串或者string变量外,还能加上一个字符!
class Solution {
public:
string countAndSay(int n) {
string str;
str = "1";
while(--n){
string temp;
char pre = str[0];
int count = 1;
for(string::size_type i = 1;i < str.size();i++){
if(str[i] == pre)
count++;
else{
char ch = count + '0';
temp = temp + ch + pre;
pre = str[i];
count = 1;
}
}
char ch = count + '0';
temp = temp + ch + pre;
str = temp;
}
return str;
}
};