-
Notifications
You must be signed in to change notification settings - Fork 0
/
numDecodings.cpp
81 lines (68 loc) · 1.79 KB
/
numDecodings.cpp
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
//
// numDecodings.cpp
// xcode
//
// Created by Gokul Nadathur on 7/19/16.
// Copyright © 2016 Gokul Nadathur. All rights reserved.
//
#include <iostream>
#include <unordered_map>
#include <string>
using namespace std;
class Solution {
unordered_map<int, int> _numSubDecodings;
bool isNextValid(string& s, int index)
{
if (index >= s.length() - 1 || !isValid(s, index)) {
return false;
}
//auto val = stoul(s.substr(index, 2));
auto val = (s[index] - '0') * 10 + s[index + 1] - '0';
return val <= 26;
}
bool isValid(string& s, int index)
{
return s[index] != '0';
}
int findSubDecodings(string& s, int index)
{
auto it = _numSubDecodings.find(index);
int numPaths = 0;
if ( it == _numSubDecodings.end()) {
numPaths = _numSubDecodings[index] = findDecodings(s, index);
} else {
numPaths = it->second;
}
return numPaths;
}
public:
int findDecodings(string& s, int start)
{
if (start >= s.length()) {
return 0;
}
if (start == s.length() - 1 && isValid(s, start)) {
return 1;
}
auto n = isValid(s, start) ? findSubDecodings(s, start + 1) : 0;
if (isNextValid(s, start)) {
int nextSeq;
if (start + 2 == s.length()) {
nextSeq = 1;
} else {
nextSeq = findSubDecodings(s, start+2);
}
n += nextSeq;
}
return n;
}
int numDecodings(string s) {
return findDecodings(s, 0);
}
};
int main(int argc, char** argv)
{
string inp = "110";
Solution s;
cout << s.numDecodings(inp) << endl;
}