MCPcopy Create free account
hub / github.com/Hsinha11/Leetcode-solutions / numDecodings

Method numDecodings

91-decode-ways/decode-ways.java:4–26  ·  view source on GitHub ↗
(String s)

Source from the content-addressed store, hash-verified

2
3class Solution {
4 public int numDecodings(String s) {
5 if (s == null || s.length() == 0) return 0;
6
7 int n = s.length();
8 int[] dp = new int[n + 1];
9 dp[0] = 1;
10 dp[1] = s.charAt(0) == '0' ? 0 : 1;
11
12 for (int i = 2; i <= n; i++) {
13 int oneDigit = Integer.parseInt(s.substring(i-1, i));
14 int twoDigits = Integer.parseInt(s.substring(i-2, i));
15
16 if (oneDigit >= 1 && oneDigit <= 9) {
17 dp[i] += dp[i-1];
18 }
19
20 if (twoDigits >= 10 && twoDigits <= 26) {
21 dp[i] += dp[i-2];
22 }
23 }
24
25 return dp[n];
26 }
27}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected