[LeetCode] Decode Ways, Solution

本文介绍了解码数字字符串问题,给出了一种使用动态规划的方法来计算给定数字字符串的不同解码方式总数。通过对比字符,利用转换函数实现了有效的计数。

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.

» Solve this problem

[Thoughts]
Similar as “ [LeetCode] Climbing Stairs, Solution“. DP. Just add some logic to compare character.

Transformation function as:
Count[i] = Count[i-1]  if S[i-1] is a valid char
       or   = Count[i-1]+ Count[i-2]  if S[i-1] and S[i-2] together is still a valid char.

[Code]

1:    int numDecodings(string s) {  
2: if(s.empty() || s[0] =='0') return 0;
3: if(s.size() ==1) return check(s[0]);
4: int fn=0, fn_1=0, fn_2=1;
5: fn_1 = (check(s[0]) * check(s[1]))+check(s[0], s[1]);
6: for(int i=2; i< s.size(); i++)
7: {
8: if(check(s[i])) fn+= fn_1;
9: if(check(s[i-1], s[i])) fn+=fn_2;
10: if(fn ==0)
11: return 0;
12: fn_2 = fn_1;
13: fn_1 = fn;
14: fn=0;
15: }
16: return fn_1;
17: }
18: int check(char one)
19: {
20: return (one != '0') ? 1 : 0;
21: }
22: int check(char one, char two)
23: {
24: return (one == '1' || (one == '2' && two <= '6'))
25: ? 1 : 0;
26: }

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值