-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path91.decode-ways.cpp
More file actions
67 lines (67 loc) · 1.31 KB
/
91.decode-ways.cpp
File metadata and controls
67 lines (67 loc) · 1.31 KB
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/*
* @lc app=leetcode id=91 lang=cpp
*
* [91] Decode Ways
*/
#include <string>
using namespace std;
// @lc code=start
class Solution
{
public:
int f[40];
Solution()
{
for (int i = 1; i < 40; i++)
f[i] = fib(i);
}
int numDecodings(string s)
{
int cnt = 0;
int res = 1;
char last = 'a';
for (auto c : s)
{
if (c == '1' || c == '2')
cnt++;
else
{
if (c == '0')
{
if (last != '1' && last != '2')
return 0;
cnt--;
}
else if (last == '2' && c - '0' > 6)
{
// do nothing
}
else
cnt++;
if (cnt > 1)
res *= f[cnt];
cnt = 0;
}
last = c;
}
if (cnt > 1)
res *= fib(cnt);
return res;
}
int fib(int n)
{
if (n <= 2)
return n;
int n1 = 1;
int n2 = 2;
int cur;
for (int i = 3; i <= n; i++)
{
cur = n1 + n2;
n1 = n2;
n2 = cur;
}
return cur;
}
};
// @lc code=end