Leetcode -- Count and Say

来源:互联网 发布:sql数据库备份软件 编辑:程序博客网 时间:2024/05/29 17:28

问题链接:https://oj.leetcode.com/problems/count-and-say/

问题描述;The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 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, generate the nth sequence.

Note: The sequence of integers will be represented as a string.

问题API:public String countAndSay(int n)

问题分析:

没有什么可以取巧的,就是brute force, 从1~n,base case 是”1”,然后第i的结果就由第I – 1的结果根据规则推导得出。

条件是while(n > 1){运算规则, n--} 代码如下:

    public String countAndSay(int n) {        String res = "1";        while(n > 1){            char cur_bit = res.charAt(0);            int counter = 1;            StringBuilder next_res = new StringBuilder();            for(int i = 1; i < res.length(); i++){                if(res.charAt(i) == cur_bit){                    counter++;                }else{                    next_res.append("" + counter + cur_bit);                    cur_bit = res.charAt(i);                    counter = 1;                }            }            next_res.append("" + counter + cur_bit);            res = next_res.toString();            n--;        }        return res;    }


0 0
原创粉丝点击