LeetCode: 91. Decode Ways

LeetCode: 91. Decode Ways

题目描述

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

'A' -> 1
'B' -> 2
...
'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.

题目大意: 将 A-Z 按照 1-26 编码,将编码后的代码输入,判断可能存在的解码方式数。

解题思路 —— 动态规划

decodingTypes[i] 表示前 i 个数可能的解码方式数,则:

  • 如果第 i+1 个数单独解码,则 decodingTypes[i+1] = decodingTypes[i];
  • 如果第 i+1 个数和第 i 个数一起解码, 则 decodingTypes[i+1] = decodingTypes[i-1];

综合以上两种情况,可以算出前 i+1 个数可能的解码方式数。

AC 代码

class Solution {
public:
    int numDecodings(string s) {
        size_t nonZero = s.find_first_not_of('0');
        if(nonZero != 0) return 0;

        vector<int> decodingTypes;  // 记录前 i 个数字解码方式数
        decodingTypes.push_back(1); // 0 个数字的解码方式为 0
        decodingTypes.push_back(1); // 1 个数字的解码方式为 1

        for(size_t i = 1; i < s.size(); ++i)
        {
            size_t typeNums = 0;
            // 如果第 i+1 个数单独解码
            if(s[i] != '0') typeNums += decodingTypes[i];

            // 如果第 i+1 个数和第 i 个数一起解码
            if((s[i-1]-'0')*10 + s[i]-'0' <= 26 && s[i-1] != '0')
            {
                typeNums += decodingTypes[i-1];
            }
            decodingTypes.push_back(typeNums);
        }

        decodingTypes[0] = 0;
        return decodingTypes[s.size()];
    }
};
全部评论

相关推荐

合适才能收到offe...:是你们把他拉黑了千里马应驰骋广阔天地,而非困于逼仄马厩。你有更大的舞台,莫执着于这破公司
点赞 评论 收藏
分享
2025-12-15 14:25
云南大学 Java
lei22:入职可能会看学信网,最好别伪装,这个简历找实习肯定是够的,肯定会有收 28 届实习生的公司的,多投就行
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务