Leetcode 91.Decode Ways (decoding mode) thinking and method of solving problems

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.

Ideas: The subject with recursion is not realized, it may be that the recursion is not written well, and finally in the online reference to write the dynamic programming code.

The idea is to judge whether the current value is 0, not 0 f[i] = f[i] + f[i-1];

Then the current value and the previous character can be composed of 26 or less of the loss, can this with f[i] = F[i] + f[i-2].

The specific code is as follows:

public class Solution {public    int numdecodings (String s) {    //dynamic plan tag    int[] f = new int[s.length ()];    Char[] C = S.tochararray ();    Boundary condition    if (c.length = = 0) {    return 0;    }    First element    f[0] = c[0] > ' 0 '? 1:0;        if (c.length = = 1) {    return f[0];    }    F[1] value is key, write bad, there will be various errors    int k = c[0] > ' 0 ' && c[1] > ' 0 '? 1:0;    F[1] = k + (c[0] = = ' 1 ' | | c[0] = = ' 2 ' && c[1] <= ' 6 '? 1:0);        Iterate backwards    for (int i = 2; i < c.length; i++) {    if (C[i] > ' 0 ') {//first element greater than 0, add    f[i] + = f[i-1];    }    //Between 10-26 add two letters to form a case    if (c[i-1] = = ' 1 ' | | (C[i-1] = = ' 2 ' && c[i] <= ' 6 ')) {    F[i] + = F[i-2];}    }        return f[c.length-1];}    }



Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Leetcode 91.Decode Ways (decoding mode) thinking and method of solving problems

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.