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

    又一道模拟题,按照一定规律生成字符串,求第n个字符串

    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.

    稍稍解释一下字符串的生成规律:字符串从“1”开始,第i+1个字符串是第i个字符串数字形式的读法。

    生成规律就是代码思路~用prev记录第i个字符串,cur为第i+1个字符串。

    逐个访问prev的元素并进行统计。c为当前字符,count为c连续出现的个数。

    当前访问的元素prev[i]与c不同时,将count, c转化成字符串格式,插入cur中;更新c和count. 

    代码

     1 class Solution {
     2 public:
     3     string countAndSay(int n) {
     4         // IMPORTANT: Please reset any member data you declared, as
     5         // the same Solution instance will be reused for each test case.
     6 
     7         string prev = "1";
     8         string cur = "";
     9         for(int i=2; i<=n; ++i)
    10         {
    11             int p=1; 
    12             int len = prev.length();
    13             char c = prev[0];
    14             int count = 1;
    15             while(p<len)
    16             {
    17                 if(c==prev[p])
    18                 {
    19                     ++p; ++count;
    20                 }
    21                 else{
    22                     cur += '0'+count;
    23                     cur += c;
    24                     count = 1;
    25                     c = prev[p++];
    26                 }
    27             }
    28             cur += '0'+count;
    29             cur += c;
    30             prev = cur;
    31             cur = "";
    32         }
    33         return prev;
    34     }
    35 };
    View Code
  • 相关阅读:
    html和css基础
    Chrome的插件使用
    04
    03
    MySQL的下载与安装(超完整)
    IDEA运行单元测试报错:java.lang.NoClassDefFoundError: org/hamcrest/SelfDescribing
    IDEA 快捷键合集
    IDEA + Spring的安装以及入门案例创建(超详细)
    Java NullPointerException异常的原因
    Eclipse 显示 错误:找不到或无法加载主类
  • 原文地址:https://www.cnblogs.com/practice/p/3392250.html
Copyright © 2011-2022 走看看