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

    分析

    难度 易

    来源

    https://leetcode.com/problems/count-and-say/description/

    题目

    The count-and-say sequence is the sequence of integers with the first five terms as following:

    1.     1
    2.     11
    3.     21
    4.     1211
    5.     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 where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence.

    Note: Each term of the sequence of integers will be represented as a string.

    Example 1:

    Input: 1
    Output: "1"

    Example 2:

    Input: 4
    Output: "1211"
    解答
     1 package LeetCode;
     2 
     3 public class L38_CountAndSay {
     4     public String countAndSay(int n) {
     5         if(n<=0){
     6             return null;
     7         }
     8         String res="1";//第一行结果
     9         int len = 0;
    10         for(int i=1;i<n;i++){//第二行及以后
    11             int count=1;//数字出现次数
    12             if(i==1){//第二行
    13                 res="11";
    14             }else {//不加else的计划,第二行有res,还会接着构建,第二行的res就会成为原本第三行展示的内容
    15                 len = res.length();
    16                 StringBuilder sb = new StringBuilder();
    17                 for (int j = 1; j < len; j++) {//统计每个字符出现次数
    18                     if (res.charAt(j - 1) == res.charAt(j)) {
    19                         count++;
    20                     } else {
    21                         sb.append(count);
    22                         sb.append(res.charAt(j - 1));
    23                         count = 1;
    24                     }
    25                 }
    26                 sb.append(count);
    27                 sb.append(res.charAt(len - 1));
    28                 res = sb.toString();
    29             }
    30         }
    31         return res;
    32     }
    33     public static void main(String[] args){
    34         L38_CountAndSay l38=new L38_CountAndSay();
    35         System.out.println(l38.countAndSay(4));
    36     }
    37 } 
    博客园的编辑器没有CSDN的编辑器高大上啊
  • 相关阅读:
    根据字符串当作变量,进行类名转换
    Python 字符分割时,只分割最后一个(rsplit的使用)
    Python之99乘法表代码
    linux 同时执行多个命令及几个基础命令
    什么是CLI、GUI
    linux命令-压缩数据
    Linux查看进程
    Linux排序数据
    Linux检测磁盘空间
    linux结束进程命令
  • 原文地址:https://www.cnblogs.com/flowingfog/p/9800062.html
Copyright © 2011-2022 走看看