lintcode512. 解码方法

末蓝、 2023-07-18 05:54 74阅读 0赞

有一个消息包含A-Z通过以下规则编码

‘A’ -> 1
‘B’ -> 2

‘Z’ -> 26
现在给你一个加密过后的消息,问有几种解码的方式

  1. 样例
  2. 样例 1:
  3. 输入: "12"
  4. 输出: 2
  5. 解释: 它可以被解码为 AB (1 2) L (12).
  6. 样例 2:
  7. 输入: "10"
  8. 输出: 1
  9. 注意事项
  10. we can't decode an empty string. So you should return 0 if the message is empty.
  11. class Solution {
  12. public:
  13. /**
  14. * @param s: a string, encoded message
  15. * @return: an integer, the number of ways decoding
  16. */
  17. int numDecodings(string &s) {
  18. // write your code here
  19. if (s.size() <= 0) {
  20. return 0;
  21. }
  22. vector<int> dp(s.size()+1);
  23. dp[0]=1;
  24. for (int i = 1; i <= s.size(); i++) {
  25. if(s[i-1]=='0') dp[i]=0;
  26. else
  27. {
  28. dp[i]+=dp[i-1];
  29. }
  30. if(i>1)
  31. {
  32. int num=atoi(s.substr(i - 2, 2).c_str());
  33. if(num>=10&&num<=26) dp[i]+=dp[i-2];
  34. }
  35. }
  36. return dp[s.size()];
  37. }
  38. };

发表评论

表情:
评论列表 (有 0 条评论,74人围观)

还没有评论,来说两句吧...

相关阅读