您的位置:首页 > 其它

Count and Say

2015-10-13 17:18 316 查看
题目名称

Count and Say—LeetCode链接

描述

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.

分析

返回一个字符串:

当n=1时,返回1;

当n=2时,按照n-1=1返回的值1,读成“1个1”,返回11;

当n=3时,按照n-1=2返回的值11,读成“2个1”,返回21;

当n=4时,按照n-1=3返回的值21,读成“1个2,1个1”,返回1211;

当n=5时,按照n-1=4返回的值1211,读成“1个1,1个2,2个1”,返回111221;

······

这道题一开始不好理解,在看懂题目意思之后,会遇到几个问题:

1.形参为int类型,返回的类型为string,涉及到数据类型转换;

2.第n个返回值要根据第n-1个返回值确定;

3.返回值如何存储来方便计算。

对于这三个问题,分别采用如下方法:

1.stringstream 是 C++ 提供的另一个字串型的串流(stream)物件,它可以实现将整数转换成字符串。要使用 stringstream, 必須先加入這一行:

#include<sstream>


2.定义两个vector,分别保存n-1的返回值和n的返回值。

3.将返回值的各个字符先以int的形式存储在vector中。

解决了这三个问题,本算法最关键的就是根据n-1的返回值求解n的返回值了,如果n为1时直接返回:当n>1时,先用一个nums存储i=2的各个位,用一个计数器count来计算相同数字出现的次数,temp存储i+1的各个位,然后将temp赋值给nums,让nums保存第i+1个返回值,再利用算法计算出下一个返回值,直到i=n.

C++代码

class Solution {
public:
string countAndSay(int n) {
stringstream res;
if(n==1){
res<<n;
return res.str();
}
int index=0;
int nums_res=0;
vector<int> nums(2,1);
for(int i=2;i<n;i++){
vector<int> temp;
int prev=nums[0];
int count=1;
for(int j=1;j<nums.size();j++){
if(nums[j]!=prev){
temp.push_back(count);
temp.push_back(prev);
prev=nums[j];
count=1;
}else{
count++;
}
if(j==nums.size()-1){
temp.push_back(count);
temp.push_back(prev);
}
}
nums=temp;
}
for(int k=0;k<nums.size();k++){
res<<nums[k];
}
return res.str();
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  letcode