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的编辑器高大上啊
  • 相关阅读:
    Docker笔记
    使用NextCloud搭建私有云盘
    docker轻量级管理工具
    docker仓库使用+harbor私有仓库部署
    防DDOS攻击解决方案
    MongoDB非关系型数据库
    监控磁盘使用率解决方案
    部署SonarQube代码质量检查7.7版本
    Jenkins的权限控制
    Jenkins分布式构建
  • 原文地址:https://www.cnblogs.com/flowingfog/p/9800062.html
Copyright © 2011-2022 走看看