LeetCode 38. Count and Say

来源:互联网 发布:月光软件站 编辑:程序博客网 时间:2024/05/12 05:41

问题

https://leetcode.com/problems/count-and-say/

解法

模拟法, n=100都会超时。

class Solution {public:    string countAndSay(int n) {        string ret;        ret.push_back('1');        for (int i=2; i<=n; ++i){            string now;            int cnt =1;            for (int j=1; j< ret.size(); ++j)            {                if (ret[j] != ret[j-1])                {                    now.append(to_string(cnt));                    now.push_back(ret[j-1]);                    cnt = 1;                }else cnt++;            }            now.append(to_string(cnt));            now.push_back(ret[ret.size()-1]);            ret = now;        }        return ret;    }};

int 转 string to_string
string 转 int stoi

0 0
原创粉丝点击