Decode Ways
Problem
A message of digits was made from letters with A = 1, B = 2, ..., Z = 26. Read the digit string and print in how many ways it can be decoded back to letters. A part like 06 is not valid. Print 0 if there is no way.
Constraints
- 1 <= length <= 45
- digits only
Examples
Input
226
Output
3
Solutions
This is like climbing stairs with rules: one digit step needs a non-zero digit, a two digit step needs a value from 10 to 26. For long digit strings the answer is a Fibonacci-like number. The inputs here stay within 2^53 so JavaScript is exact.
/*
* Problem : Process text.
* Input : One line of text.
* Output : The number of ways.
* Approach: ways[i] from ways[i-1] and ways[i-2].
* Time : O(n)
* Space : O(n)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static long solve(String s) {
// Step 1: ways[i] = the number of ways to decode the first i digits. An empty text has 1 way.
int n = s.length();
long[] ways = new long[n + 1];
ways[0] = 1;
for (int i = 1; i <= n; i++) {
// Step 2: The last digit alone is a letter if it is not 0.
if (s.charAt(i - 1) != '0') {
ways[i] += ways[i - 1];
}
// Step 3: The last two digits together are a letter if they are from 10 to 26.
if (i > 1) {
int two = Integer.parseInt(s.substring(i - 2, i));
if (two >= 10 && two <= 26) {
ways[i] += ways[i - 2];
}
}
}
return ways[n];
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s = scanner.hasNextLine() ? scanner.nextLine() : "";
System.out.println(solve(s));
}
}
Hints (1)
- Which digit can never be decoded alone?