Skip to content

Commit efb21b7

Browse files
committed
add numDecodings.cpp
1 parent 1f854d7 commit efb21b7

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

C++/numDecodings.cpp

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// Time Complexity: O(n)
2+
// Space Complexity: O(1)
3+
4+
class Solution {
5+
public:
6+
int numDecodings(string s) {
7+
if(s.empty()) return 0;
8+
9+
int prev = 0; // f[n - 2]
10+
int cur = 1; // f[n - 1]
11+
12+
for(int i = 1; i <= s.length(); ++i) {
13+
if(s[i - 1] == '0')
14+
cur = 0; // f[n - 1] = 0
15+
if(i < 2 || !(s[i - 2] == '1' || (s[i - 2] == '2' && s[i - 1] <= '6')))
16+
prev = 0; // f[n - 2] = 0;
17+
18+
int tmp = cur;
19+
cur += prev; // f[n] = f[n - 1] + f[n - 2]
20+
prev = tmp;
21+
}
22+
23+
return cur;
24+
}
25+
};

0 commit comments

Comments
 (0)