翻译数字串 transform number to string

本文介绍了一种将数字串转换为字母串的算法实现,该算法递归地尝试所有可能的转换组合,并打印出结果。考虑到特殊边界情况,如数字串结尾及倒数第二个字符的处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目源自于待字闺中的微信。

题目:给一个数字串,将其映射为一个字符串。映射关系为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;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值