首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >String - 38. Count and Say

String - 38. Count and Say

作者头像
ppxai
发布于 2020-09-23 17:12:55
发布于 2020-09-23 17:12:55
5100
举报
文章被收录于专栏:皮皮星球皮皮星球

38. Count and Say

The count-and-say sequence is the sequence of integers with the first five terms as following:

代码语言:javascript
复制
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 _n_th 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"

思路:

没有什么算法,就是暴力求解,从1开始,对每一位相同和不同的字符进行记录。

代码:

java:

代码语言:javascript
复制
class Solution {

    public String countAndSay(int n) {

        StringBuilder curr = new StringBuilder("1");
        StringBuilder prev;
        
        int count = 0, i = 1;
        char say;
        
        while (i < n) {
            prev = curr;
            curr = new StringBuilder();
            count = 1;
            say = prev.charAt(0);
            
            // say str
            for (int j = 1; j < prev.length(); j++){
                if (prev.charAt(j) != say) {
                    curr.append(count).append(say);
                    count = 1;
                    say = prev.charAt(j);
                } else {
                    // same char
                    count++;
                }
            }
            
            i++;
            curr.append(count).append(say);
        }
        
        return curr.toString();
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019年07月03日,如有侵权请联系 cloudcommunity@tencent.com 删除
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档