您的位置:首页 > 其它

count and say

2015-09-21 15:58 281 查看
报数指的是,按照其中的整数的顺序进行报数,然后得到下一个数。如下所示:

1, 11, 21, 1211, 111221, ...


1
读作
"one
1"
->
11
.

11
读作
"two
1s"
->
21
.

21
读作
"one
2, then one 1"
->
1211
.

给定一个整数
n
, 返回 第
n
个顺序。

您在真实的面试中是否遇到过这个题?

Yes

样例

给定 n =
5
, 返回
"111221"
.

注意

整数的顺序将表示为一个字符串。

class Solution {
public:
/**
* @param n the nth
* @return the nth sequence
*/
string countAndSay(int n) {
// Write your code here
if(n==1) return "1";
if(n==2) return "11";
string pre=countAndSay(n-1);
int nn=pre.size();
string res;
int count=1;
for(int i=1;i<nn;i++){
if(pre[i]==pre[i-1]) count++;
else{
res+=to_string(count)+pre[i-1];
count=1;
}
}
res+=to_string(count)+pre[nn-1];
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: