您的位置:首页 > 其它

38. Count and Say

2016-05-27 19:21 281 查看

38. Count and Say

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.

Analysis:

不复杂,主要是依次判断当前digit和上一个digit是否相同。

Source Code(C++):

#include <iostream>
#include <string>
#include <map>
#include <vector>
using namespace std;

class Solution {
public:
string countAndSay(int n) {
string s="1";
for (int i=0; i<n-1; i++) {  //第一个已经求出,只需要循环n-1次即可
int index=0;
int same_digit_counts=0;
string next_string;
while(index < s.size())
{
if (index == 0)
{
same_digit_counts=1;
}
else if (s.at(index) == s.at(index-1))
{
same_digit_counts++;
}
else {
next_string.push_back(char(same_digit_counts+'0'));
next_string.push_back(s.at(index-1));
same_digit_counts=1;
}
index++;
}
next_string.push_back(char(same_digit_counts+'0'));
next_string.push_back(s.at(index-1));
s=next_string;
}
return s;
}
};

int main() {
Solution sol;
cout << sol.countAndSay(5);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: