LeetCode 154题:Count and Say

来源:互联网 发布:apache禁止访问根目录 编辑:程序博客网 时间:2024/06/05 16:56

原题:

题目描述如下:

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.


解决方案:

一开始其实没太看懂题目意思,后来画了画才明白:一开始有1,第二个数字就有有1个1,所以是11;第三个数字是前者有2个1,所以是21,;第四个数字是前者有1个2,1个1,所以是1211,以此类推,然后就是要找出第n个数字应该是个什么样子的串,显然就是循环和递归两种方案都行,但是要注意的一点就是多位数怎么办,比如说1211,到底是1个2,1个1,还是12个1,所以这里采用逗号来分割一个个的数值,先附上循环的代码:

    public String countAndSay(int n) {        if(n <= 0)            return null;        if(1 == n)            return new String("1");        if(2 == n)            return new String("11");        String content = "1,1";        StringBuilder stringBuilder = new StringBuilder();        while(n-- > 2) {            String[] nums = content.split(",");            String num = nums[0];            int count = 1;            for(int i = 1; i < nums.length; i++) {                if(nums[i].equals(num))                    count++;                else {                    stringBuilder.append(count + "," + num + ",");                    num = nums[i];                    count = 1;                }            }            stringBuilder.append(count + "," + num + ",");            content = stringBuilder.toString().substring(0, stringBuilder.toString().length() - 1);            stringBuilder = new StringBuilder();        }        return content.replace(",", "");    }

递归代码:

public class Solution {    public String countAndSay(int n) {        return countandsay(n).replace(",","");    }        private String countandsay(int n) {        if(n <= 0)            return null;        if(1 == n)            return new String("1");        if(2 == n)            return new String("1,1");        String previous = countandsay(n-1);        String[] nums = previous.split(",");        String num = nums[0];        int count = 1;        StringBuilder stringBuilder = new StringBuilder();        for(int i = 1; i < nums.length; i++) {            if(nums[i].equals(num))                count++;            else {                stringBuilder.append(count + "," + num + ",");                num = nums[i];                count = 1;            }        }        stringBuilder.append(count + "," + num + ",");        return stringBuilder.toString().substring(0,stringBuilder.length()-1);    }}



0 0