【Leetcode】38. Count and Say

来源:互联网 发布:淘宝店铺换ip有影响吗 编辑:程序博客网 时间:2024/05/29 16:59

方法一:非递归

思路:

(1)依次求第i个String。

(2)每一次求解,用temp保存暂时的结果,求解后赋给result。

(3)遍历每个result,j记录待判断个数的字符,k用于判断,一旦与j字符不等,立即写入temp。

public class Solution {    public String countAndSay(int n) {        String result = "1";        for (int i = 2; i <= n; i++) {            String temp = "";            int j = 0, k = 1, len = result.length();             while (j < len) {                char ch = result.charAt(j);                if (k < len && ch == result.charAt(k))                    k++;                else {                    temp += (k - j);                    temp += ch;                    j = k;                }            }            result = temp;        }        return result;    }}

方法二:递归

思路:

先求第n-1个序列res,再遍历res,j记录待判断个数的字符,k用于判断,一旦与j字符不等,立即写入temp。

public class Solution {    public String countAndSay(int n) {        if (n == 1)            return "1";        String res = countAndSay(n - 1);        String result = "";        int j = 0, k = 1, len = res.length();         while (j < len) {            char ch = res.charAt(j);            if (k < len && ch == res.charAt(k))                k++;            else {                result += (k - j);                result += ch;                j = k;            }        }        return result;    }}
Runtime:54ms

1 0