Decode Ways
https://leetcode.com/problems/decode-ways/description/
Thoughts
Code
/*
* @lc app=leetcode id=91 lang=cpp
*
* [91] Decode Ways
*/
// @lc code=start
class Solution {
public:
int numDecodings(string s) {
int N = s.size();
vector<int> dp(3, 0);
dp[0] = 1;
for (int i = 1; i <= N; ++i) {
dp[i % 3] = 0;
if (i != 1 && s[i - 2] != '0') {
const auto v = stoi(s.substr(i - 2, 2));
if (v <= 26 && v >= 1) dp[i % 3] = dp[(i - 2) % 3];
}
if (s[i - 1] > '0') dp[i % 3] += dp[(i - 1) % 3];
}
return dp[N % 3];
}
};
// @lc code=end
Last updated