91.Decode Ways

Tags: [DP]

Com: {fb}

Link: https://leetcode.com/problems/decode-ways/\#/description

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

The number of ways decoding"12"is 2.


Solution: DP

class Solution(object):
    def numDecodings(self, s):
        """
        :type s: str
        :rtype: int
        """
        if not s:
            return 0

        f = [0 for _ in xrange(len(s))]
        f[0] = 0 if s[0] == '0' else 1
        if len(s) == 1:
            return f[0]

        if 1 <= int(s[1]) <= 9:
            f[1] = f[0]

        if 10 <= int(s[:2]) <= 26:
            f[1] += 1

        for i in xrange(2, len(s)):
            if 1 <= int(s[i]) <= 9:
                f[i] = f[i - 1]

            if 10 <= int(s[i - 1:i + 1]) <= 26:
                f[i] += f[i - 2]

        return f[len(s) - 1]

Revelation:

  • Be careful of the cases: s = '01', s = '1000', s = '101', s = '10'

Note:

  • Time complexity = O(n), n is the length of the given string.

results matching ""

    No results matching ""