leetcode:Decode Ways

来源:互联网 发布:armin van buuren知乎 编辑:程序博客网 时间:2024/06/02 00:26

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.

题目地址:https://oj.leetcode.com/problems/decode-ways/

这道题真是写的想死啊!!!!主要是因为送来解码的字符中有可能有0,而单独的0是不能解码的就要返回0;关于这个问题要添加很多很多要判断的条件。。不过也许是我自己的算法没有考虑全面。wrong answer无数多次之后终于ac了...

代码:

class Solution {public:    int numDecodings(string s) {        int len=s.size();if(len==0) return 0;if(s[0]=='0') return 0;vector<int> ways(len,0);ways[0]=1;for(int i=1;i<len;i++){//如果当前字符可以单独解码成一个字母if(valid(s.substr(i,1))){ways[i]=ways[i-1];}//如果当前字符和前一个字符的组合可以解码成一个字母if(valid(s.substr(i-1,2))){if(i==1){if(s[1]=='0') ways[1]=1;else ways[1]=2;}else ways[i]+=ways[i-2];}}return ways[len-1];    }private:bool valid(string s){if(s[0]=='0') return false;if(atoi(s.c_str())<=26&&atoi(s.c_str())>=1) return true;else return false;}};

0 0