首页 > 其他 > 详细

leetcode38 - Count and Say - easy

时间:2018-10-02 15:38:01      阅读:162      评论:0      收藏:0      [点我收藏+]

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;
    }
}

 

leetcode38 - Count and Say - easy

原文:https://www.cnblogs.com/jasminemzy/p/9736819.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!