Decode Ways--Leetcode

Source: Internet
Author: User

A message containing letters from was A-Z 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 " , it could be decoded as " AB "   (1 2) Or " L "   ().

The number of ways decoding is "12" 2.


Basic ideas

Similar to the question climbing stairs

Before I, there are two ways to decode:

1. Section i-1 potential energy independent decode

2. I-2 and I-1, two together as a whole decode

Then the number of DEOCDE methods is the sum of the above two paths.

This code on the Leetcode, the implementation time is 5ms.

Class Solution {public:    int numdecodings (string s) {        if (S.empty ()) return 0;        int w2 = 1;        int w1 = s[0]! = ' 0 '? 1:0;        int w = W1;        for (int i=2; i<=s.size (); i++) {            w = (s[i-1] = = ' 0 ')? 0:w1;            if (s[i-2] = = ' 1 ' | | s[i-2] = = ' 2 ' && s[i-1] >= ' 0 ' && s[i-1] <= ' 6 ')                w + = W2;                        W2 = W1;            W1 = w;        }        Return w;    }};


Decode Ways--Leetcode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.