LeetCode刷题笔记JAVA语言

38. Count and Say(自己第一次写递归)

2018-05-03  本文已影响0人  cixing

第一次自己写递归方法

先确定好结束的条件,再写具体实现某一项的内容,第一次写递归就accept了很激动。

class Solution {
    public String countAndSay(int n) {
        if(n == 1)
            return "1";
        String a = countAndSay(n-1);
        String b = "";
        int len = a.length();
        int i = 0;
        int j = 1;
        while(i<len) {
            while(j<len&&a.charAt(i)==a.charAt(j)) {
                j++;
            }
            b = b +(j-i);
            b = b +a.charAt(i);
            i = j;
            j = j+1;
        }
        return b;
    }
}

用stringbuffer会减少很多运行时间

上一篇 下一篇

猜你喜欢

热点阅读