fork download
  1. # Python program to count decoding ways of a digit string
  2. # using Tabulation
  3.  
  4. # Function to count decoding ways for the entire string.
  5. def countWays(digits):
  6. n = len(digits)
  7.  
  8. # Create a dp list initialized to 0, with size n + 1.
  9. dp = [0] * (n + 1)
  10.  
  11. # Base case: An empty string has one valid decoding.
  12. dp[n] = 1
  13.  
  14. # Iterate from the end of the string to the beginning.
  15. for i in range(n - 1, -1, -1):
  16.  
  17. # Single-digit decoding: check if current
  18. # digit is not '0'.
  19. if digits[i] != '0':
  20. dp[i] = dp[i + 1]
  21.  
  22. # Two-digit decoding: check if next two digits are valid.
  23. if (i + 1 < n and
  24. ((digits[i] == '1' and digits[i + 1] <= '9') or
  25. (digits[i] == '2' and digits[i + 1] <= '6'))):
  26. dp[i] += dp[i + 2]
  27.  
  28. return dp[0]
  29.  
  30.  
  31. if __name__ == "__main__":
  32.  
  33. digits = "12123232323232223333"
  34.  
  35. print(countWays(digits))
Success #stdin #stdout 0.07s 14148KB
stdin
Standard input is empty
stdout
640