(Daily algorithm) LeetCode --- Decode Ways

Source: Internet
Author: User

(Daily algorithm) LeetCode --- Decode Ways


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.

/* Determine whether the current character belongs to 1-9 each time (0 is definitely not good, because 0 is not in 1-26). If yes, the current character can be decode, in combination with f [n-1], f [n] + = f [n-1] then checks whether the string consisting of the current character and the previous character belongs to 10-26. If yes, then the two characters can be decode and combined with f [N-2], f [n] + = f [N-2] */class Solution {public: int numDecodings (string s) {int * a; a = new int [s. size () + 1]; memset (a, 0, (s. size () + 1) * sizeof (int); if (s. size () = 0) return 0; a [0] = 1; for (int I = 1; I <= s. size (); I ++) {if (s [I-1]! = '0') a [I] + = a [I-1]; if (I-2> = 0 & s [I-1]-'0' + 10 * (s [I-2]-'0 ') <= 26 & s [I-1]-'0' + 10 * (s [I-2]-'0')> = 10) a [I] + = a [I-2];} return a [s. size ()] ;}};




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.