Skip to content

Commit 38088bf

Browse files
authored
Update decode_ways.cpp
1 parent 7943619 commit 38088bf

File tree

1 file changed

+39
-1
lines changed

1 file changed

+39
-1
lines changed

cpp/neetcode_150/13_1-d_dynamic_programming/decode_ways.cpp

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
Time: O(n)
99
Space: O(n)
1010
*/
11-
11+
/*
1212
class Solution {
1313
public:
1414
int numDecodings(string s) {
@@ -36,3 +36,41 @@ class Solution {
3636
return dp[n];
3737
}
3838
};
39+
*/
40+
41+
/*
42+
Given a string w/ only digits, return # ways to decode it (letter -> digit)
43+
Ex. s = "12" -> 2 (AB 1 2 or L 12), s = "226" -> 3 (2 26 or 22 6 or 2 2 6)
44+
45+
DP: Bottom-up approach: check if zero and assign the i+1 value to the current;
46+
otherwise, check if the current char is a '1' and thus admits any i+1 char,
47+
or a '2', which admits only 0 <= x <= 6 as characters at i+1.
48+
49+
Time: O(n)
50+
Space: O(1)
51+
*/
52+
class Solution {
53+
public:
54+
int numDecodings(string s) {
55+
int n = s.size();
56+
int prev = 0;
57+
int curr = 1;
58+
59+
for (int i = n - 1; i >= 0; --i){
60+
int newCurr;
61+
if (s[i] == '0')
62+
newCurr = 0;
63+
else
64+
newCurr = curr;
65+
66+
if (i + 1 < n && (s[i] == '1' || s[i] == '2'
67+
&& s[i+1] <= '6'))
68+
newCurr += prev;
69+
70+
prev = curr;
71+
curr = newCurr;
72+
}
73+
74+
return curr;
75+
}
76+
};

0 commit comments

Comments
 (0)