• 【LeetCode & 剑指offer刷题】字符串题16:Count and Say


    【LeetCode & 剑指offer 刷题笔记】目录(持续更新中...)

    Count and Say

    The count-and-say sequence is the sequence of integers with the first five terms as following:
    1. 1
    2. 11
    3. 21
    4. 1211
    5. 111221
    1 is read off as "one 1" or 11.
    11 is read off as "two 1s" or 21.
    21 is read off as "one 2, then one 1" or 1211.
    Given an integer n, generate the nth term of the count-and-say sequence.
    Note: Each term of the sequence of integers will be represented as a string.
    Example 1:
    Input: 1
    Output: "1"
    Example 2:
    Input: 4
    Output: "1211"

    C++
     
    /*
     问题:Count and say 产生第n个count and say序列
     aabbccd翻译为na a nb b nc c nd d,如:
     1.     1
     2.     11
     3.     21
     4.     1211
     5.     111221
     6.     312211
    */
    //字符串保存结果
    #include <string>
    class Solution
    {
    public:
        string countAndSay(int n)
        {
            if(n <= 0) return ""; //返回空串
           
            string pre = "1"; //初始串为1
            while(--n) //产生第2~n的序列(产生后面n-1个序列)
            {
                string cur = ""; //用于缓存当前序列,初始化为空串
                for(int i = 0; i< pre.size(); i++ )//i = 0 ~ len-1,遍历整个串
                {
                    int count = 1;
                    while(i+1 < pre.size() && pre[i] == pre[i+1]) //统计连续相同数的个数(注意加上i+1<pre.size()的条件)
                    {
                        count++;
                        i++;
                    }
                    cur += to_string(count) + pre[i]; //组合成字符串,如na a
               //     cout<<cur<<endl;
                }
                pre = cur; //传值给结果
            }
            return pre;
        }
    };
     
  • 相关阅读:
    为 WordPress 标签添加 rel="nofollow" 属性
    Discuz X3.2 SEO设置 title 不支持空格的解决方法
    LANMP 如何禁止访问 .htaccess 文件
    Discuz 哪些文件和文件夹需要777权限
    WordPress 模板常用函数
    CSS控制 table 的 cellpadding,cellspacing
    从 Typecho 自定义字段的调用代码看去
    Linux 服务器如何修改 DNS
    Linux 服务器如何禁止 ping 以及开启 ping
    Asp.Net 加载不同项目程序集
  • 原文地址:https://www.cnblogs.com/wikiwen/p/10224939.html
Copyright © 2020-2023  润新知