C ++ algorithm: the number of newspaper

topic:

It reported that the number sequence is a sequence of integers, for an integer number of packets in the order in which to obtain the next number. Front five as follows:
1.1
2.11
3.21
4.1211
5.111221

Explanation:

1 is read as "One 1" ( "a a"), i.e., 11.
11 is read as "two 1s" ( "two one"), i.e., 21.
21 is read as "one 2", "one 1 " ( " a two", "a a"), i.e., 1211.
Given a positive integer n (1 ≤ n ≤ 30) , the first n items of output packet sequence number. Note: The order of integer represented as a string.

Ideas:

Vecotrtemp1 using a number of packets stored in each of the number 1 as the first memory, the second memory is 11, ..., each time updated by vecotrtemp2, when the number of packets to n, is stopped, and the converted digital temp1 a string;
number once the number of packets is obtained @: Analyzing each temp1 [j] is equal to temp1 [j + 1], is equal to 1 then the counter is incremented; end of the description does not mean the same number, at which time count and temp1 [j] is pressed into the temp2.

Code:

//思路:使用一个vecotr<int>temp1存储每次报数的数,如第一次存1,第二次存的是11,....,每次通过vecotr<int>temp2来更新,当报数到n时,停止,并将temp1中数字转换为字符串;
//求取下一次报数的数:每次判断temp1[j]是否等于temp1[j+1],等于则将计数器加1;不等于说明同一个数结束,此时将count和temp1[j]压入temp2中。

class Solution {
public:
    string countAndSay(int n) {
        
        if(n == 1)
            return "1";
        
        vector<int> temp1, temp2;
        temp1.push_back(1);
        int count = 1;
        
        for(int i = 2; i<=n;i++)
        {
            for(int j = 0; j < temp1.size(); j++)
            {
               if((j+1 == temp1.size()) || ((j+1 < temp1.size()) && (temp1[j] != temp1[j+1])))
               {
                   temp2.push_back(count);
                   temp2.push_back(temp1[j]);
                   count = 1;
               }
               else if((j+1 < temp1.size()) && (temp1[j] == temp1[j+1]))
               {
                   count++;
               }
            }
            temp1 = temp2;
            temp2.clear();
        }
        
        //将数字转为字符串
        string ret;
        for(int i = 0; i < temp1.size(); i++)
            ret.append(1, (temp1[i]+48));
        
        return ret;
    }
};

Guess you like

Origin blog.csdn.net/qq_31820761/article/details/90921382