0
点赞
收藏
分享

微信扫一扫

Day46 解码方法

给你一个只含数字的 非空 字符串 num ,请计算并返回 解码 方法的 总数

https://leetcode-cn.com/problems/decode-ways/

示例1:

示例2:

示例3:

示例4:

提示:

Java解法

package sj.shimmer.algorithm.y2021;

/**
 * Created by SJ on 2021/3/12.
 */

class D46 {
    public static void main(String[] args) {
        System.out.println(numDecodings("12"));
        System.out.println(numDecodings("226"));
        System.out.println(numDecodings("0"));
        System.out.println(numDecodings("06"));
        System.out.println(numDecodings("99"));
        System.out.println(numDecodings("2611055971756562"));
        System.out.println(numDecodings("111111111111111111111111111111111111111111111"));
        System.out.println(numDecodings("10"));
        System.out.println(numDecodings("26"));
        System.out.println(numDecodings("2101"));
    }

    public static int numDecodings(String s) {
        int length = s.length();
        int[] nums = new int[length];
        nums[0] = s.charAt(0)=='0'?0:1;
        int index = 1;
        while (index < length) {
            char c = s.charAt(index);
            char lastC = s.charAt(index-1);

            if (c == '0') {
                //如果前一位不是1或者2,显然无法解码
                if (lastC != '1' && lastC != '2') {
                    return 0;
                }else {
                    //如果前一位是1或者2
                    nums[index] = index == 1 ? 1 : nums[index - 2];
                }
            } else if (lastC == '1' || (lastC == '2' && c >= '1' && c <= '6')) {
                nums[index] = index == 1 ? nums[index - 1] + 1 : nums[index - 1] + nums[index - 2];
            } else {
                nums[index] = nums[index-1];
            }
            index++;
        }
        return nums[length - 1];
    }
}

参考解

https://leetcode-cn.com/problems/decode-ways/solution/san-chong-jie-fa-dfsyi-wei-dong-tai-gui-tfvin/

  1. 一维动态规划

举报

相关推荐

0 条评论