This page explains Java solution to problem Decode Ways
using Dynamic Programming
.
A message containing letters from A-Z is being encoded to numbers using the following mapping:
'A' -> 1
'B' -> 2
...
'Z' -> 26
Given a non-empty string containing only digits, determine the total number of ways to decode it.
The answer is guaranteed to fit in a 32-bit integer.
Example 1:Example 2:Input: s = "12"
Output: 2
Explanation: It could be decoded as "AB" (1 2) or "L" (12).
Input: s = "226"
Output: 3
Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).
package com.vc.medium;
class DecodeWays {
public int numDecodings(String s) {
int n = s.length();
int[] dp = new int[n + 1];
dp[0] = 1; // How many ways we can decode empty string
dp[1] = s.charAt(0) == '0' ? 0 : 1; // How many ways we can decode first character of a string
//dp[i] means how many ways we can decode string ending at position i
for(int i = 2; i <= n; i++) {
int oneDigit = Integer.parseInt(s.substring(i - 1, i));
int twoDigit = Integer.parseInt(s.substring(i - 2, i));
if(oneDigit >= 1 && oneDigit <= 9) dp[i] += dp[i - 1];
if(twoDigit >= 10 && twoDigit <= 26) dp[i] += dp[i - 2];
}
return dp[n];
}
}
O(N) Where
N length of input string S
O(N) Where
N length of input string S