[leetcode]count and say

#include <iostream>
#include <vector>
#include <stack>
#include <queue>
using namespace std;

class Solution {
public:
    string countAndSay(int n) {//调用process N次
        if (n<1)
            return "";

        string str = "1";
        if (n == 1)
            return str;
        for (int i = 1; i < n; i++){
            string str1 = process(str);
            str.assign(str1);
        }
        return str;
    }

    string process(const string &str){//每次对于一个str,经过处理后,返回它的count and say
        string result = "";

        int left = 0;
        int right = 0;
        while (right < str.length()){
            if (str[right] == str[left]){
                right++;
                continue;
            }

            int count = right - left;
            char tmp[10];
            sprintf(tmp, "%d%d", count, str[left] - '0');
            string tmp1(tmp);
            result.append(tmp1);

            left = right;
        }
        if (str[right-1] == str[left]){
            int count = right - left;
            char tmp[10];
            sprintf(tmp, "%d%d", count, str[left] - '0');
            string tmp1(tmp);
            result.append(tmp1);
        }
        
        return result;
    }
};


int main()
{
    int n = 5;
    Solution s;
    string result = s.countAndSay(n);
    return 0;
}

EOF

原文地址:https://www.cnblogs.com/lihaozy/p/2824304.html