LeetCode#91. Decode Ways

本文介绍了一种使用动态规划求解字母编码问题的方法。通过分析字母到数字的映射规律,给出了具体的递推公式,并提供了C++代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

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.

题意解析:

可采用动态规划的思想来解决,英文字母可映射到1到26个数字,令F(n)表示n个数字共有多少种解码方式,a[]为输入的一串数字,那么我们便可以的到如下的递推公式。

若a[n] != 0,且 (a[n-1]*10+a[n] >= 1 && a[n-1]*10+a[n] <= 26)   F(n) = F(n-1)+F(n-2);

若a[n] != 0, 且 (a[n-1]*10+a[n] == 0 || a[n-1]*10+a[n] > 26)  F(n) = F(n-1);

若a[n] == 0,且 (a[n-1]*10+a[n] >= 1 && a[n-1]*10+a[n] <= 26)   F(n) = F(n-2);

若a[n] == 0, 且 (a[n-1]*10+a[n] == 0 || a[n-1]*10+a[n] > 26)  F(n) =0;

由以上几个递推公式,便可得出正确的结果,最后输出F(n)即可。

一种c++的实现方式如下:

#include<iostream>
#include<string>
using namespace std;

class Solution {
public:
    int numDecodings(string s) {
        int num = s.length();
        if(num == 0) return 0;
        if(s[0] == '0') return 0;
		int *res = new int[num+1];
		res[0] = 1;
		res[1] = 1;
		for(int i = 1; i < num; i++) {
			string temp;
			temp = s.substr(i-1,2);
			if(isvalid2(temp) && isvalid1(s[i])) {
				res[i+1] = res[i]+res[i-1];
			} else if(isvalid2(temp) && !isvalid1(s[i])) {
				res[i+1] = res[i-1];
			} else if(!isvalid2(temp) && isvalid1(s[i])) {
				res[i+1] = res[i];
			} else {
				res[num] = 0;
				break;
			}
		}  
		return res[num];
    }
    //判断一个数字是否合法
    bool isvalid1(char s) {
    	if(s == '0') {
    		return false;
		} else {
			return true;
		}
	}
    //判断两个数字是否合法
	bool isvalid2(string s) {
		if(s[0] == '0') {
			return false;
		}
		int n;
		n = (s[0]-'0')*10 + (s[1]-'0');
		if(n > 26) return false;
		return true;
	}
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值