[Leetcode] Decode ways

Source: Internet
Author: User

A message containing letters fromA-ZIs 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 cocould be decoded"AB"(1 2) or"L"(12 ).

The number of ways Decoding"12"Is 2.

Https://oj.leetcode.com/problems/decode-ways/

 

Idea 1: DFS.

Idea 2: DP. Like the Fibonacci series, DP [I] indicates the total number of combinations from the beginning to the I bit.

If the I-1 bit is not equal to 0, DP [I] needs to add DP [I-1.

If the I-2 bit to the I-1 bit is between 1-26, DP [I] needs to add the DP [I-2] situation.

 

public class Solution {    // be careful of "0" "01" "100"    public int numDecodings(String s) {        if (s.length() == 0)            return 0;        int[] dp = new int[s.length() + 1];        dp[0] = 1;        if (s.charAt(0) != ‘0‘)            dp[1] = 1;        else            dp[1] = 0;        for (int i = 1; i < s.length(); i++) {            if (s.charAt(i) != ‘0‘)                dp[i + 1] = dp[i];            if (s.charAt(i - 1) != ‘0‘ && Integer.parseInt(s.substring(i - 1, i + 1)) <= 26)                dp[i + 1] += dp[i - 1];        }        return dp[s.length()];    }    public static void main(String[] args) {        String s = "1010";        System.out.println(new Solution().numDecodings(s));    }}
View code

 

Refer:

Http://blog.csdn.net/u011095253/article/details/9248109

Http://blog.csdn.net/worldwindjp/article/details/19938131

 

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.