Decode Ways Java Solutions

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.

The subject is very similar to that of climbing stairs. Use an array to do the DP.

But the difference is that there are several limitations:
First: S[i-1] can not be 0, if S[I-1] is 0, num[i] can only be equal to num[i-2]
Second, the first character in S[i-2,i-1] cannot be 0, and Integer.parseint (S.substring (i-2,i)) must have an integer from 0 to 27

1  Public classSolution {2      Public intnumdecodings (String s) {3         if(s = =NULL|| S.length () = = 0)return0;4         int[] num =New int[S.length () +1];5Num[0] = 1;6NUM[1] = S.charat (0)! = ' 0 '? 1:0;7          for(inti = 2; I <= s.length (); i++){8             if(S.charat (i-1)! = ' 0 ')9Num[i] = num[i-1];Ten             if(S.charat (i-2)! = ' 0 ' && integer.parseint (s.substring (i-2,i)) < 27) OneNum[i] + = Num[i-2]; A         } -         returnnum[s.length ()]; -     } the}

Decode Ways Java Solutions

Related Article

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.