Count and Say 笔记

2017-06-27  本文已影响43人  赵智雄

The count-and-say sequence is the sequence of integers with the first five terms as following:

  1. 1
  2. 11
  3. 21
  4. 1211
  5. 111221

1is read off as"one 1"or11.
11is read off as"two 1s"or21.
21is read off as"one 2, thenone 1"or1211.
Given an integern, generate thenthterm of the count-and-say sequence.
Note: Each term of the sequence of integers will be represented as a string.

题目意思大概就是,n = 1时候输出一个1,n = 2的时候输出11(1个1),n = 3 时候输出 21(2个1),n = 4时候输出1211(1个2,1个1)。。。以后每个数相当于把前头的数数一遍。

思路:写个循环,从2开始一直循环到n,用两个字符串分别保存上一个数的结果和这次的结果。循环里,再来一个循环数字符串。两个变量,一个a保存现在正在数的字符,一个ac用来保存正在数的字符的个数。每次循环完把res2的值赋值给res,下次循环用。简单粗暴的解决了。

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

class Solution {
public:
    string countAndSay(int n) {
        string res = "1";
        string res2 = "1";
        //从2开始数 
        for(int i = 2; i<= n;i++)
        {
            res2 = "";
            char a = res[0];//数 第一个数 
            int ac = 1; //计数
            int j = 1;// 
            while(res[j]!='\0')//结束
            {
                if(res[j] == a)//计数加1 
                {
                    ac++;
                    j++; 
                }
                else //加这个 
                {
                    char temp[200] = ""; 
                    sprintf(temp,"%d",ac);
                    res2 += temp;
                    res2 += a;
                    a = res[j];
                    ac = 1;
                    j++;
                } 
            }
            char temp[200] = ""; 
            sprintf(temp,"%d",ac);
            res2 += temp;
            res2 += a; 
            res = res2;
        } 
        return res2;
    } 
};
int main()
{
    Solution so;
    for(int i = 0;i<=10;i++)
    {
        string ss = so.countAndSay(i);
        cout << i << " "<< ss << endl;  
    }
}
上一篇下一篇

猜你喜欢

热点阅读