DevPath

← All problems

Decode Ways

Medium dynamic-programming · strings

Description

Digits map to letters (1=A ... 26=Z). Return the number of ways to decode the string.

Constraints

1 <= length <= 100; digits 0-9

Examples

Input: s = "226"

Output: 3

BZ, VF, BBF

Hints (1)
  • A single digit decodes if non-zero; a pair decodes if between 10 and 26.

Solutions

Two rolling counts. · Time O(n) · Space O(1)

func numDecodings(s string) int {
    if s == "" || s[0] == '0' {
        return 0
    }
    prev2, prev1 := 1, 1
    for i := 1; i < len(s); i++ {
        curr := 0
        if s[i] != '0' {
            curr += prev1
        }
        two := int(s[i-1]-'0')*10 + int(s[i]-'0')
        if two >= 10 && two <= 26 {
            curr += prev2
        }
        prev2, prev1 = prev1, curr
    }
    return prev1
}

Create a free account to submit solutions, track progress and save problems.

Create account