-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDecode_Ways.cpp
87 lines (72 loc) · 1.51 KB
/
Decode_Ways.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
82
83
84
85
#include <iostream>
using namespace std;
class Solution {
public:
int numDecodings(string s) {
if(s == "")
return 0;
int joint = 0;
int sep = 0;
if(s[0]=='0')
return 0;
else
sep = 1;
s = preprocess(s);
int size = s.size();
int temp_sep;
if(size == 0)
return 0;
for(int i=1;i<size;i++){
//cout << "iteration:" << i << endl;
//cout << joint << " "<< sep;
//cout << "-----------------"<<endl;
if(s[i-1]=='a'){
sep = sep + joint;
joint = 0;
continue;
}
if(s[i]=='a'){
continue;
}
int digit1 = int(s[i]-'0');
int digit2 = int(s[i-1]-'0');
// can joint
if(digit2*10 + digit1 <= 26){
temp_sep = sep;
sep = joint + temp_sep;
joint = temp_sep;
}
// cant not
else{
sep = joint + sep;
joint = 0;
}
}
return sep + joint;
}
string preprocess(string s){
if(s.size()>1){
string r;
r += s[0];
for(int i=1;i<s.size();i++){
if(s[i]=='0'){
if(r[r.size()-1]=='1' || r[r.size()-1]=='2'){
r[r.size()-1]='a';
continue;
}
else{
return "";
}
}
r += s[i];
}
return r;
}
return s;
}
};
int main(){
Solution s = Solution();
cout << s.numDecodings("1212");
return 0;
}