Skip to content

Commit 8223d78

Browse files
committed
Solution: Decode Ways
1 parent 911ee8e commit 8223d78

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

decode-ways/flynn.cpp

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* For the length of the given string N,
3+
*
4+
* Time complexity: O(N)
5+
*
6+
* Space complexity: O(N)
7+
*/
8+
9+
class Solution {
10+
public:
11+
int numDecodings(string s) {
12+
if (s[0] == '0') return 0;
13+
14+
int memo[s.size() + 1];
15+
16+
fill(memo, memo + s.size() + 1, 0);
17+
memo[0] = 1;
18+
memo[1] = 1;
19+
20+
for (int i = 2; i <= s.size(); i++) {
21+
int s_i = i - 1;
22+
if (s[s_i] != '0') memo[i] = memo[i - 1];
23+
int two_digits = stoi(s.substr(s_i - 1, 2));
24+
if (10 <= two_digits && two_digits <= 26) memo[i] += memo[i - 2];
25+
}
26+
27+
return memo[s.size()];
28+
}
29+
};

0 commit comments

Comments
 (0)