// Solution to "Alphacode"" by Bob Roos // // Basic idea: dynamic programming (fairly straightforward application). // Starting from the right end of the string, find the number of // encodings of each suffix. When we obtain a new suffix by adding a digit // on the left, if it is zero then there are no encodings for the new // suffix. If it is nonzero, then it can encode a letter from A through I, // so we add the number of encodings of the remaining string. In addition, // if it and the following digit are between 1 and 26, then we can add // the number of encodings of the string following those two digits. import java.io.*; import java.util.*; public class AlphaCodeB { public static BufferedReader in; public static String line; // The string of digits to be processed public static long count[]; // count[i] = #decodings from i-th to the end public static int n; // number of digits = length of "line" public static int digits[]; // The digits from "line" in int form ///////////////////////////////////////////////////////////////// // main -- loops over the input instances: public static void main(String[] args) throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); // Get first instance: line = in.readLine().trim(); // Loop over instances: while (! line.equals("0")) { n = line.length(); // Convert string to array of int digits: digits = new int[n]; for (int i = 0; i < n; i++) { digits[i] = line.charAt(i) - '0'; } // Initialize the array for the dynamic programming computation: count = new long[n+1]; // n = string length for (int i = 0; i <=n; i++) count[i] = 0; // Base cases: see if last digit is non-zero; if so, one // encoding: if (digits[n-1] > 0) count[n-1] = 1; // See if last two digits are between 1 and 26; if so, count this // encoding: if (n >= 2 && digits[n-2] > 0 && digits[n-2]*10 + digits[n-1] >= 1 && digits[n-2]*10 + digits[n-1] <= 26) count[n-2] = 1; // All the other digits, from right to left, are processed here: for (int i = n-2; i >= 0; i--) { if (digits[i] != 0) { // a valid encoding can't start with 0 count[i] += count[i+1]; int twodig = digits[i]*10 + digits[i+1]; if (twodig >= 1 && twodig <= 26) count[i] += count[i+2]; // System.out.println("temp " + count[i]); } } System.out.println(count[0]); // Get next instance: line = in.readLine().trim(); } } }