C++算法:报数

题目:

报数序列是一个整数序列,按照其中的整数的顺序进行报数,得到下一个数。其前五项如下:
1. 1
2. 11
3. 21
4. 1211
5. 111221

解释:

1 被读作 “one 1” (“一个一”) , 即 11。
11 被读作 “two 1s” (“两个一”), 即 21。
21 被读作 “one 2”, “one 1” (“一个二” , “一个一”) , 即 1211。
给定一个正整数 n(1 ≤ n ≤ 30),输出报数序列的第 n 项。注意:整数顺序将表示为一个字符串。

思路:

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

代码:

//思路:使用一个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;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_31820761/article/details/90921382