---
title: "[Leetcode] Decode Ways"
author: "cozilla"
date: "2013-09-11T17:33:06Z"
tags: []
categories: ["非技术"]
slug: "leetcode-decode-ways"
draft: false
lastmod: "2013-09-11T17:33:06Z"
id: 1940938
url: "https://cozilla.iteye.com/blog/1940938"
---

**Decode Ways**Jun 25 '126747 / 26583

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.

 

 

dp\[i] = dp\[i-1] + dp\[i-2];

 

 

```
class Solution {
public:   
    bool isValid(const string& s, int a) {
        if (s[a] == '0') return false;
        else return true;
    }
    bool isValid(const string& s, int a, int b) {
        if (s[a] < '1' ||
            s[a] > '2' ||
            (s[a] == '2' && s[b]  > '6')) return false;
        else return true;
    }
    int numDecodings(string s) {
        int n = s.size();
        if (n == 0) return 0;
        if (s[0] == '0') return 0;
        vector<int> dp(n, 0);
        dp[0] = 1;
        if (s[1] != '0') dp[1]++;
        if (isValid(s,0,1)) dp[1]++;
        
        for (int i = 2; i < n; i++) {
            if (isValid(s, i)) dp[i] += dp[i-1];
            if (isValid(s, i-1, i)) dp[i] += dp[i-2];
            
        }

        return dp[n-1];
    }

};
```