Decode Ways

来源:互联网 发布:java工程师工作职责 编辑:程序博客网 时间:2024/05/18 11:45

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或2.。这样其实就像是跳台阶,每次能跳一步

或者两步。

class Solution {public:    bool check(char n){return n>='1'&&n<='9';}    bool check(char a, char b){return a=='1'||(a=='2'&&(b<='6'&&b>='0'));}    int numDecodings(string s) {        int len = s.size();        if(len == 0) return 0;        if(len == 1) return check(s[0]);        int f[len];        memset(f,0,sizeof(int)*len);                f[0] = check(s[0]);        f[1] = check(s[0],s[1])+(check(s[0])&check(s[1]));        for(int i = 2;i<len;i++)        {            if(check(s[i])) f[i] = f[i]+f[i-1];            if(check(s[i-1],s[i])) f[i] = f[i]+f[i-2];        }                return f[len - 1];    }};


0 0
原创粉丝点击