Decode Ways
Implement decodeWays
A message made up only of the digits 1-9 was encoded by mapping 'A' to "1", 'B' to "2", all the way up to 'Z' being "26" — so a decoded letter can come from either a single digit (1-9) or a pair of digits read together (10-26). Given the encoded digit string, count how many distinct ways it can be decoded back into letters. A '0' can never stand for a letter on its own, so it's only ever valid as the second digit of a two-digit pairing.
Every position in the string faces the same choice as the one before it: read the current digit as its own letter and move one step forward, or — if it pairs with the next digit to form a number from 10 to 26 — read the two together as one letter and move two steps forward. Both choices, when valid, contribute their own count of ways to finish decoding the rest of the string, and adding those counts together gives the total ways to decode from the current position onward. Building this up from the front of the string, one position at a time, turns what would otherwise be an exponential branching search into a single linear pass.
Example 1:
Input: s = "15"
Output: 2
Example 2:
Input: s = "1123"
Output: 5
Example 3:
Input: s = "2611"
Output: 4
+ 7 hidden test cases run on Submit.
Constraints:
- ●
1 ≤ s.length ≤ 100 - ●
s consists of digits only ('0'-'9')
s =
15