Skip to content

Commit

Permalink
Create heozeop.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
heozeop authored Aug 24, 2024
1 parent dd8141d commit 9ff9dda
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions decode-ways/heozeop.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// Time Complexity: O(n)
// Spatial Complexity: O(n)

class Solution {
public:
int numDecodings(string s) {
if(s.length() < 1 || s[0] == '0') {
return 0;
}

vector<int> dp(s.length() + 1, 0);
dp[0] = dp[1] = 1;
if(s[1] == '0') {
dp[1] = 0;
}

int prev,pprev;
for(int i = 2; i <= s.length(); ++i) {
prev = s[i - 1] - '0';
if (prev <= 9 && prev > 0) {
dp[i] += dp[i-1];
}
pprev = (s[i - 2] - '0') * 10 + prev;
if(pprev <= 26 && pprev > 9) {
dp[i] += dp[i-2];
}
}

return dp[s.length()];
}
};

0 comments on commit 9ff9dda

Please sign in to comment.