[LeetCode]38. Count and Say

来源:互联网 发布:网络光纤收发器 编辑:程序博客网 时间:2024/05/20 11:34

[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;}
原创粉丝点击