Leetcode Decode Ways

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 "12" , it could be decoded as "AB" (1 2) or "L" (12).

The number of ways decoding is "12" 2.

Problem Solving Ideas:

The typical dynamic programming

Judging dp[i-1], dp[i-2] is valid

Recurrence Formula:dp[i] + = Dp[i-1] if (s (i-1, i) is valid (1-9)) + Dp[i-2] (if s (i-2, i)) are valid (10-26))

Base Case:dp[0] =1, dp[1] = 1 (s (0) is valid) or 0 (s (0) are not valid)

Java Code:

 Public classSolution { Public intnumdecodings (String s) {if(s = =NULL|| S.length () = = 0 | | S.equals ("0")){            return0; }        int[] DP =New int[S.length () +1]; //base case:dp[0] dp[1]Dp[0] = 1; if(IsValid (s.substring (0,1)) {dp[1] = 1; }Else{dp[1] = 0; }         for(inti = 2; I<= s.length (); i++){            if(IsValid (S.substring (i-1, i))) {Dp[i]+ = Dp[i-1]; }            if(IsValid (S.substring (i-2, i))) {Dp[i]+ = Dp[i-2]; }        }        returndp[s.length ()]; }         Public BooleanIsValid (String s) {if(S.charat (0) = = ' 0 ') {            return false; }        intValue = Integer.parseint (s);//Integer.parseInt:translate string to int        returnValue >=1 && value <= 26; }}

Reference:

1. http://www.programcreek.com/2014/06/leetcode-decode-ways-java/

2. http://www.cnblogs.com/springfor/p/3896162.html

Leetcode Decode Ways

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.