zoukankan      html  css  js  c++  java
  • LeetCode:Count and Say

    题目链接

    The count-and-say sequence is the sequence of integers beginning as follows:
    1, 11, 21, 1211, 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 sequence.

    Note: The sequence of integers will be represented as a string.


    题目描述的不是很清楚,其实就是第i+1个字符串是第i个字符串的读法,第一字符串为 “1”

    比如第四个字符串是1211,它的读法是 1个1、1个2,2个1,因此第五个字符串是111221。

    第五个字符串的读法是:3个1、2个2、1个1,因此第六个字符串是312211                  本文地址

    ......

    简单的模拟就可以。

     1 class Solution {
     2 public:
     3     string countAndSay(int n) {
     4         if(n < 1)return "";
     5         string prev = "1";
     6         for(int i = 2; i <= n; i++)
     7         {
     8             char curChar = prev[0];
     9             int times = 1;//curChar 出现的次数
    10             string tmpstr;
    11             prev.push_back('#');//处理边界条件
    12             for(int k = 1; k < prev.size(); k++)
    13             {
    14                 if(prev[k] == curChar)
    15                     times++;
    16                 else
    17                 {
    18                     tmpstr += to_string(times);
    19                     tmpstr.push_back(curChar);
    20                     curChar = prev[k];
    21                     times = 1;
    22                 }
    23             }
    24             prev = tmpstr;
    25         }
    26         return prev;
    27     }
    28 };

    其实我们可以发现字符串中永远只会出现1,2,3这三个字符,假设第k个字符串中出现了4,那么第k-1个字符串必定有四个相同的字符连续出现,假设这个字符为1,则第k-1个字符串为x1111y。第k-1个字符串是第k-2个字符串的读法,即第k-2个字符串可以读为“x个1,1个1,1个y” 或者“*个x,1个1,1个1,y个*”,这两种读法分别可以合并成“x+1个1,1个y” 和 “*个x,2个1,y个*”,代表的字符串分别是“(x+1)11y” 和 "x21y",即k-1个字符串为“(x+1)11y” 或 "x21y",不可能为“x1111y”.

    【版权声明】转载请注明出处:http://www.cnblogs.com/TenosDoIt/p/3776356.html

  • 相关阅读:
    php中的int参数
    php中parse_url函数的源码及分析
    记一次对python反弹shell的分析
    系统管理常用命令
    Linux内核参数注释与优化
    常见/dev/mapper/centos-root扩容
    使用Hbase快照将数据输出到互联网区测试环境的临时Hbase集群
    Postgres安装详解
    CentOS6.5生产环境系统安装
    Kafka跨网络访问设置
  • 原文地址:https://www.cnblogs.com/TenosDoIt/p/3776356.html
Copyright © 2011-2022 走看看