zoukankan      html  css  js  c++  java
  • 【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;
        }
    };
     
  • 相关阅读:
    PC端网站微信扫码登录
    H5微信授权登录
    Taro -- Swiper的图片由小变大3d轮播效果
    vue,一路走来(17)--vue使用scss,并且全局引入公共scss样式
    vscode 黑屏及类名报错解决方案
    js的cookie写入存储与读取
    常用正则表达式
    JS获取当前时间戳的方法
    URL的截取问题
    cookie的基本用法案例
  • 原文地址:https://www.cnblogs.com/wikiwen/p/10224939.html
Copyright © 2011-2022 走看看