题目源自于待字闺中的微信。
题目:给一个数字串,将其映射为一个字符串。映射关系为1->a, 2->b,..., 25->y, 26->z。
对于一个输入串,判断能否进行转换。如果能的话,输出所有可能转换成的字符串。
注意考虑指针到字符串结尾和字符串在倒数第1个字符的特殊情况。
本方法为每种可能的转换情况申请了空间,空间复杂度不理想。
#include <stdio.h>
#include <malloc.h>
#include <string.h>
#define N 20
void fun(char *str, char result[], const int len)
{
if(*str == '\0')
{
printf("%s\n", result);
return;
}
if(str[0] < '1' || str[0] > '9')
throw "输出错误!";
//翻译1个字符
int a = str[0] - '0';
char out[N];
strcpy(out, result);
out[len-1] = a + 'a' - 1;
out[len] = '\0';
fun(str+1, out, len+1);
//翻译2个字符
if(*(str+1)!='\0') //若已经到了倒数第1个字符,就不能翻译2个字符
{
int b = str[1] - '0';
int c = a*10 + b;
if(c < 27)
{
char out[N];
strcpy(out, result);
out[len-1] = c + 'a' - 1;
out[len] = '\0';
fun(str+2, out, len+1);
}
}
}
int main()
{
char a[N];
scanf("%s",a);
char result[N] = "";
try{
fun(a, result, 1);
}
catch(...)
{
printf("输入错误,无法转换。\n");
}
return 1;
}