We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 1f854d7 commit efb21b7Copy full SHA for efb21b7
C++/numDecodings.cpp
@@ -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