-
Notifications
You must be signed in to change notification settings - Fork 261
Expand file tree
/
Copy pathdecode-ways.cpp
More file actions
34 lines (29 loc) · 767 Bytes
/
decode-ways.cpp
File metadata and controls
34 lines (29 loc) · 767 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// Time: O(n)
// Space: O(1)
class Solution {
public:
/**
* @param s a string, encoded message
* @return an integer, the number of ways decoding
*/
int numDecodings(string& s) {
if (s.empty()) {
return 0;
}
int prev = 0; // f[n - 2]
int cur = 1; // f[n - 1]
for (int i = 0; i < s.length(); ++i) {
if (s[i] == '0') {
cur = 0; // f[n - 1] = 0
}
if (i == 0 ||
!(s[i - 1] == '1' || (s[i - 1] == '2' && s[i] <= '6'))) {
prev = 0; // f[n - 2] = 0
}
int tmp = cur;
cur += prev; // f[n] = f[n - 1] + f[n - 2]
prev = tmp;
}
return cur;
}
};