-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecodeways.cpp
More file actions
63 lines (61 loc) · 1.27 KB
/
decodeways.cpp
File metadata and controls
63 lines (61 loc) · 1.27 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
class Solution {
public:
int numDecodings(string s) {
int len = s.length();
if (len == 0)
{
return 0;
}
vector<int>ret(len,0);
auto tmp = s.substr(0, 1);
if (isvalid(tmp))
{
ret[0] = 1;
}
if (len < 2)
{
return ret[0];
}
tmp = s.substr(0, 2);
if (isvalid(tmp))
{
ret[1] = 1;
}
tmp = s.substr(1, 1);
if (isvalid(tmp))
{
ret[1] += ret[0];
}
for (int i = 2; i < len; i++)
{
if (isvalid(s.substr(i, 1)))
{
ret[i] += ret[i - 1];
}
if (isvalid(s.substr(i - 1, 2)))
{
ret[i] += ret[i - 2];
}
}
return ret[len - 1];
}
private:
bool isvalid(string s)
{
if (s.length() > 2 ||
s.length() == 0)
{
return false;
}
if (s.at(0) == '0')
{
return false;
}
int t = stoi(s);
if (t > 26 || t <= 0)
{
return false;
}
return true;
}
};