Skip to content

Commit 8a06d41

Browse files
committed
added solution for leetcode/dynamic programming/91.cpp
1 parent 04cd2df commit 8a06d41

File tree

1 file changed

+38
-0
lines changed
  • leetcode/cpp/dynamic programming

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
//Decode ways
2+
3+
class Solution {
4+
public:
5+
bool check(string s, int i){
6+
int num = (s[i-1] - '0')*10 + (s[i] - '0');
7+
if(num>=10 && num<=26)return true;
8+
return false;
9+
}
10+
11+
int numDecodings(string s) {
12+
if(s.length() == 0)return 0;
13+
vector<int> dp(s.length()+1, 0);
14+
dp[0] = 1;
15+
if(s[0]>'0'){
16+
dp[1] = 1;
17+
}
18+
else {
19+
return 0;
20+
}
21+
if(s.length() == 1)return s.length();
22+
for(int i=1;i<s.length();i++){
23+
if(s[i] == '0' && s[i-1]>'0' && s[i-1]<'3'){
24+
dp[i+1] = dp[i-1];
25+
}
26+
else if(s[i] == '0'){
27+
return 0;
28+
}
29+
else if(check(s, i)){
30+
dp[i+1] = dp[i-1] + dp[i];
31+
}
32+
else{
33+
dp[i+1] = dp[i];
34+
}
35+
}
36+
return dp[s.length()];
37+
}
38+
};

0 commit comments

Comments
 (0)