91. Decode Ways

A message containing letters can be encoded following mapping:

'A' -> "1" .... '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.

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

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

def numDecodings(s: str):
       
    if s[0] == "0":
        return 0
   
    L = len(s)        
    twoBack = 1
    oneBack = 1
    # current = 1
   
    for i in range(1, L):
        current = 0
        if s[i] != "0":
            current = oneBack            
                       
        dd = int(s[i-1] + s[i])
        if dd >= 10 and dd <= 26:
            current += twoBack
           
        twoBack, oneBack = oneBack, current
       
    return oneBack # current also works if initialized with 1
               
               

def numDecodings_O_N_Space(s: str):
   
    L = len(s)        
    dp = [0] * L
   
    for i in range(L):
        if int(s[i]) >= 1 and int(s[i]) <= 9:
            dp[i] = dp[i-1] if i > 0 else 1
        else:
            dp[i] = 0
           
        if i > 0:
            dd = int(s[i-1] + s[i])
            if dd >= 10 and dd <= 26:
                if i >= 2:
                    dp[i] += dp[i-2]
                else:
                    dp[i] += 1

Comments

Popular posts from this blog

849. Maximize Distance to Closest Person

347. Top K Frequent Elements

139. Word Break