91. Decode Ways

xiaoxiao2021-07-04  297

Description

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.

Example 1:

Input: “12” Output: 2 Explanation: It could be decoded as “AB” (1 2) or “L” (12).

Example 2:

Input: “226” Output: 3 Explanation: It could be decoded as “BZ” (2 26), “VF” (22 6), or “BBF” (2 2 6).

Problem URL


Solution

给一个数字的字符串,判断这个字符串可以代表多少种字母的表示方式。非常经典的动态规划题目。

We could use dynamic programming to resolve this problem. Using an array with length of s’s length add one to store dynamic programming result. dp[0] = 1; value of dp[1] is depended on the first char of s is valid or not. Then we could start our dynamic programming in a for loop. Using Integer.valueOf() to get the number of one digit and two digits before dp[] posision. Then determining whether it is valid or not. If valid, dp should contain the value of one or two digit before. Finally, return dp[n], which is the answer.

Code

class Solution { public int numDecodings(String s) { if (s.length() == 0) return 0; int len = s.length(); int[] dp = new int[len + 1]; dp[0] = 1; dp[1] = s.charAt(0) == '0' ? 0 : 1; for (int i = 2; i <= len; i++){ int first = Integer.valueOf(s.substring(i - 1, i)); int second = Integer.valueOf(s.substring(i - 2, i)); if (first > 0 && first < 10) dp[i] += dp[i-1]; if (second >= 10 && second <= 26) dp[i] += dp[i-2]; } return dp[len]; } }

Time Complexity: O(n) Space Complexity: O(n)


Review

This problem can also be solved by O(1) space complexity.

转载请注明原文地址: https://www.6miu.com/read-4821315.html

最新回复(0)