Decode Ways

描述

A message containing letters from A-Z is being encoded to numbers using the following mapping:

  1. 'A' -> 1
  2. 'B' -> 2
  3. ...
  4. 'Z' -> 26

Given an encoded message containing digits, determine the total number of ways to decode it.

For example,Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12).

The number of ways decoding "12" is 2.

分析

跟第???节Climbing Stairs很类似,不过多加一些判断逻辑。

代码

  1. // Decode Ways
  2. // 动规,时间复杂度O(n),空间复杂度O(1)
  3. class Solution {
  4. public:
  5. int numDecodings(const string &s) {
  6. if (s.empty() || s[0] == '0') return 0;
  7. int prev = 0;
  8. int cur = 1;
  9. // 长度为n的字符串,有 n+1个阶梯
  10. for (size_t i = 1; i <= s.size(); ++i) {
  11. if (s[i-1] == '0') cur = 0;
  12. if (i < 2 || !(s[i - 2] == '1' ||
  13. (s[i - 2] == '2' && s[i - 1] <= '6')))
  14. prev = 0;
  15. int tmp = cur;
  16. cur = prev + cur;
  17. prev = tmp;
  18. }
  19. return cur;
  20. }
  21. };

相关题目

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/cpp/dp/decode-ways.html