Decode Ways

原题: https://leetcode.com/problems/decode-ways/description/
题意: 给定包含数字的编码消息,确定解码方式的总数。
约定:(1)字母A-Z到数字的映射为:
'A' -> 1
'B' -> 2
...
'Z' -> 26
例子: 
给定编码消息:"12"
它可以被解码成“AB”或者“L”,所以返回2
标签: ways、decode、解码、编码、总数、面试
猜你感兴趣的圈子:
LeetCode交流圈
  • Bingo
    2017-08-11 13:45:50 1楼#1层
    Java解法一:
    public class Solution {
        public int numDecodings(String s) {
            if (s.isEmpty() || (s.length() > 1 && s.charAt(0) == '0')) return 0;
            int[] dp = new int[s.length() + 1];
            dp[0] = 1;
            for (int i = 1; i < dp.length; ++i) {
                dp[i] = (s.charAt(i - 1) == '0') ? 0 : dp[i - 1];
                if (i > 1 && (s.charAt(i - 2) == '1' || (s.charAt(i - 2) == '2' && s.charAt(i - 1) <= '6'))) {
                    dp[i] += dp[i - 2];
                }
            }
            return dp[s.length()];
        }
    }
  • Bingo
    2017-08-11 13:46:07 2楼#1层
    C++解法一:
    class Solution {
    public:
        int numDecodings(string s) {
            if (s.empty() || (s.size() > 1 && s[0] == '0')) return 0;
            vector<int> dp(s.size() + 1, 0);
            dp[0] = 1;
            for (int i = 1; i < dp.size(); ++i) {
                dp[i] = (s[i - 1] == '0') ? 0 : dp[i - 1];
                if (i > 1 && (s[i - 2] == '1' || (s[i - 2] == '2' && s[i - 1] <= '6'))) {
                    dp[i] += dp[i - 2];
                }
            }
            return dp.back();
        }
    };
  • Bingo
    2017-08-11 13:46:30 3楼#1层
    C++解法二:
    class Solution {
    public:
        int numDecodings(string s) {
            if (s.empty()) return 0;
            vector<int> dp(s.size() + 1, 0);
            dp[0] = 1;
            for (int i = 1; i < dp.size(); ++i) {
                if (s[i - 1] != '0') dp[i] += dp[i - 1];
                if (i >= 2 && s.substr(i - 2, 2) <= "26" && s.substr(i - 2, 2) >= "10") {
                    dp[i] += dp[i - 2];
                }
            }
            return dp.back();
        }
    };
  • Bingo
    2017-08-11 13:47:08 4楼#1层
    C++解法三(空间复杂度 O(1)):
    class Solution {
    public:
        int numDecodings(string s) {
            if (s.empty() || s.front() == '0') return 0;
            int c1 = 1, c2 = 1;
            for (int i = 1; i < s.size(); ++i) {
                if (s[i] == '0') c1 = 0;
                if (s[i - 1] == '1' || (s[i - 1] == '2' && s[i] <= '6')) {
                    c1 = c1 + c2;
                    c2 = c1 - c2;
                } else {
                    c2 = c1;
                }
            }
            return c1;
        }
    };
  • 回复
隐藏