leetcode 题解 || Count and Say 问题

来源:互联网 发布:java list<>遍历 编辑:程序博客网 时间:2024/05/23 14:04


problem:

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.

Hide Tags
 String
这是一个比较有意思的题目,计数-读数-产生新字符串。注意:我刚开始的做法是把 n 先转化成 string,
再对该字符串进行计数-读数操作,
后来发现题目已近给定初始字符串”1“,不过我还是把我的 int转换成 string部分代码帖出来了,
注释部分就是。


thinking:

(1)首先要读懂计数 - 读数的规律,比较有意思

(2)对重复的数计数,单个的数读一个什么数。


code:

class Solution {public:    string countAndSay(int n) {       // string start = int_to_string(n);       string start ="1";        for(int i=0;i<n-1;i++ )            start = factory(start);        return start;    }protected:    string factory(string str)    {        int count=1;//初始化为1 ,很巧妙         string res;        if(str.empty())            return str;        if(str.size()==1)        {            res.push_back('1');            res+=str;            return res;        }        for(string::size_type i=0;i<str.size()-1;i++)//计数到倒数第二个        {            if(str.at(i)==str.at(i+1))            {                count++;                if(i==str.size()-2) //到了末尾,别忘了存储                {                    char a=count+'0';                    res.push_back(a);                    res.push_back(str.at(i));                }            }            else            {                char a=count+'0';                res.push_back(a);                res.push_back(str.at(i));                count=1;            }        }//size()-1        if(str.at(str.size()-1)!=str.at(str.size()-2))//处理最后一个字符        {            res.push_back('1');            res.push_back(str.at(str.size()-1));        }       // factory(res,n--);        return res;    }    /*    string int_to_string(int n)  // int invert into string     {        vector<char> array;        string res;        if(n<0)            n=-n;        while(n>0)        {            int a = n%10;            n/=10;            char b = '0'+a;            array.push_back(b);        }        for(int i=array.size()-1;i>=0;i--)          res.push_back(array.at(i));        return res;    }    */};


0 0