欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

[LeetCode]38. Count and Say

程序员文章站 2022-03-23 18:31:41
...

[LeetCode]38. Count and Say

题目描述

[LeetCode]38. Count and Say

思路

字符串拼接,暴力遍历即可

代码

#include <iostream>
#include <string>

using namespace std;

class Solution {
public:
    string countAndSay(int n) {
        if (n == 0)
            return "";
        string res = "1";
        while (--n) {
            string cur = "";
            for (int i = 0; i < res.size(); ++i) {
                int count = 1;
                while (i + 1 < res.size() && res[i] == res[i + 1]) {
                    ++count;
                    ++i;
                }
                cur += to_string(count) + res[i];
            }
            res = cur;
        }
        return res;
    }
};

int main() {
    Solution s;
    cout << s.countAndSay(5) << endl;

    system("pause");
    return 0;
}
相关标签: leetcode