Example 1
- Input
- s = "12"
- Output
- 2
The split [1,2] represents AB, and [12] represents L. These are the only possible first-piece lengths, and both finish successfully.
Count how many ways the digit string s splits into pieces from 1 to 26 with no leading zeros, where each piece stands for one letter.
Letters A through Z correspond to decimal codes 1 through 26. Given a nonempty string of digits, count the ways to divide the entire string into valid letter codes. A piece may contain one nonzero digit, or two digits forming a number from 10 through 26.
Zero cannot stand alone and leading zeros in a piece are forbidden: 06 is invalid, while 10 and 20 are valid. Return zero if no complete decoding exists. The final answer is guaranteed to fit a signed 32-bit integer.
The split [1,2] represents AB, and [12] represents L. These are the only possible first-piece lengths, and both finish successfully.
The complete splits are [2,2,6] for BBF, [22,6] for VF, and [2,26] for BZ. The number 226 is outside the code range.
Zero is not a standalone letter code, and 06 has a leading zero. Neither possible first piece is legal.
The splits [1,1,10,6] and [11,10,6] are valid. Splits using 0 alone or the piece 06 are invalid, so the zero removes other apparent choices.
Only the pair 10 represents a letter, J. The single-digit choice 1 leaves an undecodable zero.
Each decoding chooses whether the next letter consumes one digit or two. In "12", taking "1" leaves "2" and gives AB, while taking "12" gives L. Those are two distinct complete splits. At any position a zero blocks the single-digit choice, and a two-digit choice is allowed only for 10 through 26. Many paths reach the same suffix, so remembering counts removes repeated search; counting prefixes needs only the previous two counts.
Reveal Recursive Branching: intuition, complexity, and code
When a string split consumes one of a fixed set of lengths, count completions by those disjoint choices. A prefix recurrence reading only a fixed number of preceding states can roll its storage, provided the numeric representation remains exact.