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;
        }
    }
  • 相关阅读:
    2017-3-7 leetcode 66 119 121
    2017-3-6 leetcode 118 169 189
    2017-3-5 leetcode 442 531 533
    c++ std
    2017-3-4 leetcode 414 485 495
    2017-3-3 leetcod 1 35 448
    想做手游
    编程规范
    1165: 零起点学算法72——首字母变大写
    1164: 零起点学算法71——C语言合法标识符(存在问题)
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/9736819.html
Copyright © 2011-2022 走看看