题解 | #把数字翻译成字符串#

把数字翻译成字符串

http://www.nowcoder.com/practice/046a55e6cd274cffb88fc32dba695668

递归

public  int solve (String nums) {
        // write code here
        return process(nums, 0);
    }
    public int process(String nums, int index) {
        if (index == nums.length()) {
            return 1;
        }
        if (nums.charAt(index) == '0') return 0;
        if (index + 1 == nums.length() || ((nums.charAt(index) - '0') * 10 + nums.charAt(index + 1) - '0') > 26) {
            return process(nums, index + 1);
        }
        return process(nums, index + 1) + process(nums, index + 2);
    }

动态规划

    public int solve (String nums) {
        // write code here
        char[] str = nums.toCharArray();
        int N = str.length;
        int[] dp = new int[N];
        dp[0] = 1;
        for (int i = 1; i < N; i++) {
            if (str[i] != '0') {
                dp[i] = dp[i - 1];
            }
            int num = (str[i - 1] - '0') * 10 + str[i] - '0';
            if (num >= 10 && num <= 26) {
                dp[i] += i == 1 ? 1 : dp[i - 2];
            }
        }
        return dp[N - 1];
    }
全部评论

相关推荐

双非坐过牢:非佬,可以啊10.28笔试,11.06评估11.11,11.12两面,11.19oc➕offer
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务