Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
decode-ways-ii.cpp 1.36 KB
一键复制 编辑 原始数据 按行查看 历史
Allen Liu 提交于 2017-07-19 00:07 +08:00 . update
// Time: O(n)
// Space: O(1)
class Solution {
public:
int numDecodings(string s) {
static const int M = 1000000007;
static const int W = 3;
vector<long long> dp(W);
dp[0] = 1;
dp[1] = s[0] == '*' ? 9 : (s[0] != '0' ? dp[0] : 0);
for (int i = 1; i < s.length(); ++i) {
if (s[i] == '*') {
dp[(i + 1) % W] = 9 * dp[i % W];
if (s[i - 1] == '1') {
dp[(i + 1) % W] = (dp[(i + 1) % W] + 9 * dp[(i - 1) % W]) % M;
} else if (s[i - 1] == '2') {
dp[(i + 1) % W] = (dp[(i + 1) % W] + 6 * dp[(i - 1) % W]) % M;
} else if (s[i - 1] == '*') {
dp[(i + 1) % W] = (dp[(i + 1) % W] + 15 * dp[(i - 1) % W]) % M;
}
} else {
dp[(i + 1) % W] = s[i] != '0' ? dp[i % W] : 0;
if (s[i - 1] == '1') {
dp[(i + 1) % W] = (dp[(i + 1) % W] + dp[(i - 1) % W]) % M;
} else if (s[i - 1] == '2' && s[i] <= '6') {
dp[(i + 1) % W] = (dp[(i + 1) % W] + dp[(i - 1) % W]) % M;
} else if (s[i - 1] == '*') {
dp[(i + 1) % W] = (dp[(i + 1) % W] + (s[i] <= '6' ? 2 : 1) * dp[(i - 1) % W]) % M;
}
}
}
return static_cast<int>(dp[s.length() % W]);
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助