栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

LeetCode——38. Count and Say(C++)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

LeetCode——38. Count and Say(C++)

LeetCode——38. Count and Say
The count-and-say sequence is a sequence of digit strings defined by the recursive formula:

countAndSay(1) = “1”
countAndSay(n) is the way you would “say” the digit string from countAndSay(n-1), which is then converted into a different digit string.
To determine how you “say” a digit string, split it into the minimal number of substrings such that each substring contains exactly one unique digit. Then for each substring, say the number of digits, then say the digit. Finally, concatenate every said digit.

For example, the saying and conversion for digit string “3322251”:

Given a positive integer n, return the nth term of the count-and-say sequence.

Example 1:

Input: n = 1
Output: “1”
Explanation: This is the base case.
Example 2:

Input: n = 4
Output: “1211”
Explanation:
countAndSay(1) = “1”
countAndSay(2) = say “1” = one 1 = “11”
countAndSay(3) = say “11” = two 1’s = “21”
countAndSay(4) = say “21” = one 2 + one 1 = “12” + “11” = “1211”

Constraints:
1 <= n <= 30

题目大概意思就是从1作为第一个串开始读,读出的串作为下一个待读串,读n-1次,返回第n-1次读出的结果。

class Solution {
public:
    string countAndSay(int n) {
        if(n<=0)return "";
        if(n==1)return "1";
        string pre="1",now="";
        n--;
        while(n--)
        {
            now="";
            for(int i=0;i
                int cnt=1;
                while(i
                    cnt++;
                    i++;
                }
                now+=to_string(cnt)+pre[i];
                i++;
            }
            pre=now;
        }
        return now;
    }
};

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/968231.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号