38.[Leetcode]Count and Say

来源:互联网 发布:linux查看根目录命令 编辑:程序博客网 时间:2024/05/01 22:40

这道题倒是不难,但是我debug了好久,总有一些小问题。debug的效率也是效率之一,提高debug的能力,以后在做题的时候,给自己规定debug的时间

public class Solution {    public String countAndSay(int n) {        if(n == 0 || n == 1) return "1";        StringBuilder str = new StringBuilder("1");        StringBuilder newStr = new StringBuilder("");        int count = 1;        for(int j=0;j<n-1;j++){            for(int i=0;i<str.length();i++){                if(!isEN(i,str)){                    newStr.append(String.valueOf(count));                    count = 1;                    newStr.append(str.charAt(i));                } else {                    count++;                }            }            str = new StringBuilder(newStr.toString());            newStr = new StringBuilder("");        }        return str.toString();    }    public boolean isEN(int i,StringBuilder str){        if(i+1 == str.length() || str.charAt(i) != str.charAt(i+1)) return false;        return true;    }}

但是逻辑更优的则是 递归的方法,这简直是典型的递归问题

string countAndSay(int n) {    if (n == 1) {        return string("1");    }    string prev = countAndSay(n-1);    int before = 0;    int count = 0;    string curr;    for (int i = 0; i < prev.length(); ++i) {        if (prev[i]-'0' == before) {            count++;            continue;        } else if (before != 0) {            curr.append(1, '0' + count);            curr.append(1, '0' + before);        }        before = prev[i]-'0';        count = 1;    }    if (before != 0 && count != 0) {        curr.append(1, '0' + count);        curr.append(1, '0' + before);    }    return curr;}
0 0