zoukankan      html  css  js  c++  java
  • 38. 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.

    分析

    题目的理解可能会引起误解,就是以“1”为起始,按照上述描述规律,“1”-》“11”-》“21”-》“1211”-》...得到第N个字符串是多少
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    class Solution {
    public:
        string countAndSay(int n) {
            string result = "1";
            for(int i = 1; i < n; ++i){
                result = nextStr(result);
            }
            return result;
        }
         
        string nextStr(string s){
            char last = 0;
            int count = 1;
            string result = "";
            for(int i = 0; i < s.size(); ++i){
                if(last != s[i]){
                    if(i != 0)result += to_string(count) + last;
                    count = 1;
                    last = s[i];
                }
                else{
                    count++;
                }
            }
            result += to_string(count) + last;
            return result;
        }
    };




  • 相关阅读:
    S3C2440实现dm9000网卡驱动程序移植
    IMX257虚拟网卡vnet驱动程序
    ram_flash驱动
    S3C2440 nor_flash驱动程序
    Java 打印* 三角形
    Java系列学习说明
    java案例1,打印hello java
    zabbixproxy安装
    python鉴黄程序
    mssql发布订阅事项
  • 原文地址:https://www.cnblogs.com/zhxshseu/p/0088c5c21ed9bc7557894f18bf7f5de2.html
Copyright © 2011-2022 走看看