문제

 

https://leetcode.com/problems/decode-ways/

 

Decode Ways - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

A message containing letters from A-Z can be encoded into numbers using the following mapping:

'A' -> "1"
'B' -> "2"
...
'Z' -> "26"

To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "11106" can be mapped into:

  • "AAJF" with the grouping (1 1 10 6)
  • "KJF" with the grouping (11 10 6)

Note that the grouping (1 11 06) is invalid because "06" cannot be mapped into 'F' since "6" is different from "06".

Given a string s containing only digits, return the number of ways to decode it.

The test cases are generated so that the answer fits in a 32-bit integer.

인코딩된 메세지를 디코딩하여 디코딩할 있는 방법의 수를 리턴해라.

 

Example 1:

Input Output
s = "12" 2
Explanation: "12" could be decoded as "AB" (1 2) or "L" (12).

Example 2:

Input Output
s = "226" 3
Explanation: "226" could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).

 

문제풀이 코드

class Solution:
    def numDecodings(self, s: str) -> int:
        dp = [0 for _ in range(len(s) + 1)]
        dp[0], dp[1] = 1, 1

        if s[0] == '0' or len(s) <= 0: return 0

        for i in range(1, len(s)):
            if s[i] != '0':
                dp[i + 1] = dp[i + 1] + dp[i]
            if s[i - 1] != '0' and 1 <= int(s[i-1:i+1]) <= 26:
                dp[i + 1] = dp[i + 1] + dp[i - 1]
        return dp[len(s)]

dp로 문제 접근

1. dp[i + 1] = dp[i+1] + dp[i]는 s[i]가 0이 아닐 때 성립하고

2. dp[i + 1] = dp[i+1] + dp[i-1]는 s[i-1]이 0이 아니고 s[i-1]과 s[i]을 합쳤을 때 1보다 크거나 같고 26보다 작거나 같을 때 성립한다.

3. 위 조건대로 구현하여 dp배열에서 배열 s의 길이번째 값을 리턴한다.

 

 

+ Recent posts