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();
        }
  • 相关阅读:
    pku,杨建武:文本挖掘技术
    IT国家重点实验室
    Python3实现简单的http server
    需要保存数据zabbix,不需要保存数据nagios
    Union
    wox 快速搜索程序
    QTTabBar http://qttabbar.wikidot.com/
    git出错调试
    虚拟机无法上网的问题的解决
    通过命令行升级git for windows
  • 原文地址:https://www.cnblogs.com/maydow/p/4631190.html
Copyright © 2011-2022 走看看