400 028 6601

建站动态

根据您的个性需求进行定制 先人一步 抢占小程序红利时代

leetcode面试准备:DecodeWays

1 题目

A message containing letters from A-Z is being encoded to numbers using the following mapping:

在孝南等地区,都构建了全面的区域性战略布局,加强发展的系统性、市场前瞻性、产品创新能力,以专注、极致的服务理念,为客户提供成都做网站、网站建设 网站设计制作按需搭建网站,公司网站建设,企业网站建设,成都品牌网站建设,成都全网营销,成都外贸网站建设公司,孝南网站建设费用合理。

'A' -> 1'B' -> 2...'Z' -> 26

Given an encoded message containing digits, determine the total number of ways to decode it.

For example,
Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12).
The number of ways decoding "12" is 2.

接口:public int numDecodings(String s);

2 思路

一维动态规划,偷懒了,照搬博文。
分析:需要注意的是,如果序列中有不能匹配的0,那么解码方法是0,比如序列012 、100(第二个0可以和1组成10,第三个0不能匹配)。

复杂度: Time O(n); Space O(n)

3 代码

        public int numDecodings(String s) {        // 1.初始化
        final int len = s.length();        if (len == 0)            return 0;        int[] dp = new int[len + 1];
        dp[0] = 1;        if (s.charAt(0) != '0')
            dp[1] = 1;        else
            dp[1] = 0;        // 2.一维DP方程
        for (int i = 2; i <= len; i++) {            if (s.charAt(i - 1) != '0')
                dp[i] = dp[i - 1];            else
                dp[i] = 0;            if (s.charAt(i - 2) == '1'
                    || (s.charAt(i - 2) == '2' && s.charAt(i - 1) <= '6'))
                dp[i] += dp[i - 2];
        }        return dp[len];
    }

4 总结

写递归的解法

新航道雅思


分享题目:leetcode面试准备:DecodeWays
转载源于:http://mbwzsj.com/article/jeejsp.html

其他资讯

让你的专属顾问为你服务