zoukankan      html  css  js  c++  java
  • leetcode38

    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:做n次count and say。
    循环2:即每次count and say,根据上一次的字符串,统计每个连续char的对象和次数,一个个append上去。
    循环3:即用于统计某个具体char的次数。(while套while时重复母while的边界检查)。

    实现:

    class Solution {
        public String countAndSay(int n) {
            String crt = "1";
            for (int i = 0; i < n - 1; i++) {
                StringBuilder sb = new StringBuilder();
                
                int j = 0;
                while (j < crt.length()) {
                    char c = crt.charAt(j);
                    int cnt = 1;
                    while (j + 1 < crt.length() && crt.charAt(j) == crt.charAt(j + 1)) {
                        cnt++;
                        j++;
                    }
                    sb.append(cnt);
                    sb.append(c);
                    j++;
                }
                
                crt = sb.toString();
            }
            return crt;
        }
    }
  • 相关阅读:
    创建Java项目报错处理
    samba服务器的安装及配置
    如何给Ubuntu 安装Vmware Tools
    Ubuntu切换至root用户
    网络打印机的配置
    tigervnc*
    163镜像地址
    浅谈数据库的完整性
    Android之获取本地图片并压缩方法
    网址收藏
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/9736819.html
Copyright © 2011-2022 走看看