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;
        }
    }
  • 相关阅读:
    二分图匹配【模板】
    高斯消元【模板】
    G. 小花梨的函数
    数字计数
    选课
    二叉苹果树
    重建道路
    【UVA10187】Headmaster's Headache(校长的烦恼)
    【51NOD1447】好记的字符串
    【51NOD1779】逆序对统计
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/9736819.html
Copyright © 2011-2022 走看看