[LeetCode] 91. Decode Ways - 파이썬(Python)

2022. 5. 13. 18:10·Solving Algorithm Problem/LeetCode

문제 링크 : 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

유형 : 동적 계획법(Dynamic Programming)

문제 설명

숫자만 포함된 문자열 s가 주어지면 이를 디코딩하는 방법의 수를 return 하는 문제이다.

 

A~Z까지의 문자들은 아래와 같이 숫자로 인코딩할 수 있다.

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

인코딩된 메시지를 디코딩 하려면 위의 매핑을 반대로 사용하여 모든 숫자를 그룹화한 다음 다시 문자로 매핑해야 한다(그룹화하는 방법은 여러 가지가 있다). 예를 들어 "11106"은 다음과 같이 매핑할 수 있다.

  • (1 1 10 6)으로 그룹화하여 매핑한 "AAJF"
  • (11 10 6)으로 그룹화하여 매핑한 "KJF"

(1 11 06)으로는 그룹화 될 수 없다. 왜냐하면 "6"과 "06"은 다르기 때문에 "06"이 'F'와 매핑된다고 볼 수 없다.

Example 1)
Input: s = "12"
Output: 2
Example 2)
Input: s = "226"
Output: 3
Example 3)
Input: s = "06"
Output: 0

제한사항

  • 1 <= s.length <= 100
  • s은 0과 양의 정수들로 이루어져 있다.

문제 풀이

성공 코드

from typing import List

class Solution:
    def numDecodings(self, s: str) -> int:
        str_length = len(s)
        if str_length == 0:
            return 0
        
        dp = [None]*(str_length+1)
        dp[-1] = 1
        
        last_char = s[-1]
        if int(last_char) == 0:
            dp[str_length-1] = 0
        else:
            dp[str_length-1] = 1
            
        for idx in range(str_length-2,-1,-1):
            single_num = int(s[idx])
            single_count = 0
            if single_num > 0:
                single_count = dp[idx+1]
            
            double_num = int(s[idx:idx+2])
            double_count = 0
            if 10 <= double_num <= 26:
                double_count = dp[idx+2]
                
            count = single_count + double_count
            dp[idx] = count
            
        return dp[0]

시간 복잡도 : O(n)

n은 s의 크기이다.

공간 복잡도 : O(n)

n은 s의 크기이다.

저작자표시
'Solving Algorithm Problem/LeetCode' 카테고리의 다른 글
  • [LeetCode] 152. Maximum Product Subarray - 파이썬(Python)
  • [LeetCode] 53. Maximum Subarray - 파이썬(Python)
  • [LeetCode] 322. Coin Change - 파이썬(Python)
  • [LeetCode] 64. Minimum Path Sum - 파이썬(Python)
김행만
김행만
이모저모 다 적기
  • 김행만
    hyeinisfree
    김행만
  • 전체
    오늘
    어제
    • 분류 전체보기 (41)
      • AWS (0)
      • Network (6)
      • CICD (1)
      • Spring (0)
      • Ruby on Rails (0)
      • Java (12)
      • Python (1)
      • Computer Science (6)
        • Algorithm (2)
        • Data Structure (3)
        • Database (0)
        • Design Pattern (1)
      • Solving Algorithm Problem (12)
        • LeetCode (12)
        • Programmers (0)
      • 자격증 (1)
      • Tip (1)
      • Etc (1)
        • 도서, 강의 (1)
        • Talk (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

    • GitHub
  • 공지사항

  • 인기 글

  • 태그

    CISCO
    Network
    java
    Packet Tracer
    cisco packet tracer
    java 필수 문법
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
김행만
[LeetCode] 91. Decode Ways - 파이썬(Python)
상단으로

티스토리툴바