****(leetcode_string) Decode Ways

来源:互联网 发布:网络手机铃声大全试听 编辑:程序博客网 时间:2024/06/06 07:36

Decode Ways

 Total Accepted: 24925 Total Submissions: 153233My Submissions

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.

Show Tags
 Dynamic Programming String
Have you met this question in a real interview? 
Yes
 
No

Discuss

1、回溯法,超时。。。。

class Solution {    int ret;    void dfs(string s, int curDep, int maxDep){        if(curDep==maxDep){            ret++;            return;        }        if(s[curDep]=='0')             return;        dfs(s,curDep+1,maxDep);        if(curDep+1<maxDep){            int tmp = (s[curDep]-'0')*10+(s[curDep+1]-'0');            if(tmp>=10&&tmp<27)                dfs(s,curDep+2,maxDep);        }    }public:    int numDecodings(string s) {        if(s=="") return 0;        dfs(s,0,s.length());        return ret;    }};


2、动态规划思路:

当我们知道了n-2长度的字符串能够解释的数目以及n-1长度的字符串能够解释的数目时,我们可以判读如下两个条件:
1)若第n个字符在1到9之间,则n长度的字符串能够解释的数目包含n-1长度字符串能够解释的数目。
2)若第n-1个字符与第n个字符可以解释为一个字母时,则n长度的字符串能够解释的数目包含n-2长度字符串能够解释的数目。
 

所以用r1表示n-1长度的字符串表示的数目, r2表示n-2长度的字符串表示的数目

class Solution {    public:    int numDecodings(string s) {        if(s==""||s[0]=='0') return 0;        int r1=1,r2=1;        for(int i=1;i<s.length();i++){            if(s[i]=='0')                r1=0;            if(s[i-1]=='1'||(s[i-1]=='2'&&s[i]<='6')){                r1=r1+r2;                r2=r1-r2;            }            else                r2=r1;        }        return r1;    }};


0 0
原创粉丝点击