【LeetCode】Decode Ways

来源:互联网 发布:js mouseover 冒泡 编辑:程序博客网 时间:2024/06/16 10:52

题目描述:

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.

显然是道动态规划题。

若1<=s[i-1]s[i]<=26,则dp[i]=dp[i]+dp[i-2];

若1<=s[i]<=26,则dp[i]=dp[i]+dp[i-1]。

需要注意以下问题:

1、s[0]和s[1]处的边界问题

2、s[i-1]和s[i]为0时的处理

代码如下:

class Solution {public:int numDecodings(string s) {if (!s.length())return 0;vector<int> dp(s.length(), 0);for (int i = 0; i < s.length(); i++){if (s[i] != '0'){if (i == 0) dp[i] = 1;else dp[i] = dp[i] + dp[i - 1];}int d = (s[i - 1] - 48) * 10 + s[i] - 48;if (i >= 1 && s[i - 1] != '0'&&d >= 1 && d <= 26){if (i == 1) dp[i] = dp[i] + 1;else dp[i] = dp[i] + dp[i - 2];}}return dp[dp.size() - 1];}};


0 0
原创粉丝点击