题目大意:
将一串字符串(只有A-Z)转化成数字0-9,转换的规则:A->1,B->2 ......Z->26。
那么从这段数字再转换回去字符串就会发生一些歧义,题目要求求出一段数字转换成字符串的最多数量。
解题思路:
如果说用dp[i]表示当前的前i个数字能够转化的字符串数量,当str[i+1]加进来时,如果说跟前面的一个字符能够构成26以下的数字,那说明这个状态至少有两种组合选择:
于是状态的转移就是:dp[i] = dp[i-1] + dp[i-2]
当然,这里需要考虑0的状况,因为0是不能作为十位数并且不能单独翻译的,所以有了另外的两个状态转移。
源码如下:
/* * main.cpp * * Created on: Sep 23, 2011 * Author: raphealguo */ #include <stdio.h> #include <iostream> #include <string.h> using namespace std; #define MAXL 10000 int dp[MAXL]; int main(){ int n; char str[MAXL]; int i, len; int c1, c2; while (scanf ("%s", str) && !(strlen(str) == 1 && str[0] == '0')) { memset(dp, 0, sizeof(dp)); len = strlen(str); dp[0] = 1; dp[1] = 1; for (i = 2; i <= len; ++i){ c1 = str[i-1] - '0'; c2 = str[i-2] - '0'; //子状态的3组选择 if (c2 != 0 && c1 != 0 && c2*10 + c1 <= 26){ dp[i] = dp[i-1] + dp[i-2]; }else if (c1 == 0){//处理个位的0 dp[i] = dp[i-2]; }else{//处理十位的0 dp[i] = dp[i-1]; } } printf ("%d\n", dp[len]); } return 0; }
附带原题:
Alice and Bob need to send secret messages to each other and are discussing ways to encode their messages: Alice: "Let's just use a very simple code: We'll assign `A' the code word 1, `B' will be 2, and so on down to `Z' being assigned 26." Bob: "That's a stupid code, Alice. Suppose I send you the word `BEAN' encoded as 25114. You could decode that in many different ways!" Alice: "Sure you could, but what words would you get? Other than `BEAN', you'd get `BEAAD', `YAAD', `YAN', `YKD' and `BEKD'. I think you would be able to figure out the correct decoding. And why would you send me the word `BEAN' anyway?" Bob: "OK, maybe that's a bad example, but I bet you that if you got a string of length 500 there would be tons of different decodings and with that many you would find at least two different ones that would make sense." Alice: "How many different decodings?" Bob: "Jillions!" For some reason, Alice is still unconvinced by Bob's argument, so she requires a program that will determine how many decodings there can be for a given string using her code.
Input will consist of multiple input sets. Each set will consist of a single line of digits representing a valid encryption (for example, no line will begin with a 0). There will be no spaces between the digits. An input line of `0' will terminate the input and should not be processed
For each input set, output the number of possible decodings for the input string. All answers will be within the range of a long variable.
25114 1111111111 3333333333 0
6 89 1