Decode Ways: the idea to remember.
Count decodings of a nonempty digit string using letter codes 1 through 26.
The core insight
A nonzero final digit can stand alone; a final pair from 10 to 26 can extend the prefix two positions earlier.
Why it works
Every decoding ends in exactly one or two digits, and valid endpoint checks cover both disjoint possibilities.
The mistake to avoid
Zero cannot be decoded alone. A pair such as 06 is invalid even though its numeric value is six.
Commented Java solution
Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.
int numDecodings(String s) {
int two = 1, one = s.charAt(0) == '0' ? 0 : 1;
for (int i = 1; i < s.length(); i++) {
int current = s.charAt(i) == '0' ? 0 : one;
int pair = (s.charAt(i - 1) - '0') * 10 + s.charAt(i) - '0';
if (pair >= 10 && pair <= 26) current += two;
two = one; one = current;
}
return one;
}Make the next connection
Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.