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.

    网上看了下别人的解释才看懂

    1  念成  一个1   11

    11   念成两个1   21

    21  念成  一个2 一个1   1211

    1211  念成 一个1一个2两个1   111221

    代码实现

        public String countAndSay(int n) {
            int i=1;
            String result="1";
            while(i<n)
            {
                result=countAndSayString(result);
                i++;
            }
            return result;
        }
        public String countAndSayString(String str)
        {
            if(str.equals("1"))
                return "11";
            char cur=str.charAt(0);//当前数
            int count=1;//当前数个数
            StringBuilder stringBuilder=new StringBuilder();
            for(int i=1;i<str.length();i++)
            {
                if(cur==str.charAt(i))
                {
                    count++;
                    if(i==str.length()-1)
                    {
                        stringBuilder.append(count).append(cur);
                    }
                }
                else
                {
                    stringBuilder.append(count).append(cur);
                    cur=str.charAt(i);
                    count=1;
                    if(i==str.length()-1)
                    {
                        stringBuilder.append(count).append(cur);
                    }
                }
            }
            return stringBuilder.toString();
        }
  • 相关阅读:
    Python:三元运算
    SaltStack部署服务及配置管理apache+php-第二篇
    SaltStack介绍及简单配置-第一篇
    git基础常用维护命令
    MySQL设置只读模式
    运维杂记-05
    Tomcat的配置,设置内存,获取用户IP
    Linux系统巡检项目
    Redis维护
    nginx配置文件说明
  • 原文地址:https://www.cnblogs.com/maydow/p/4631190.html
Copyright © 2011-2022 走看看