【小米笔试题】密码破译-C语言实现

题目

我们来做一个简单的密码破译游戏。破译的规则很简单,将数字转换为字母,1转化为a,2转化为b,依此类推,26转化为z。现在输入的密码是一串数字,输出的破译结果是该数字串通过转换规则所能产生的所有字符串。

输入:
多行数据,每行为一个数字串。
输出:
多行数据,没行对应输出通过数字串破译得到的所有字符串,并按照字符串顺序排列,字符串之间用单个空格
分隔,每行开头和结尾不允许有多余的空格。

样例输入:
1
12
123
样例输出:
a
ab l
abc aw lc

思路

深度优先算法。先按照一个数字一组破译,破译到最后一个再回退一步,按照两个一组破译。代码没有考虑0的情况,还需要优化。

代码

#include <stdio.h>
#include <string.h>

void transform(char *s, int index, char *res, char *tmp, int flag)
{
	if (index == strlen(s) - 1)
	{
		char ch[2] = {0};
		ch[0] = s[index] - '0' + 96;
		strcat(res, ch);
		strcat(tmp, ch);
		ch[0] = ' ';
		strcat(res, ch);
		
		return;
	}

	if (index > strlen(s) - 1)
	{
		char ch[2] = {0}; 
		ch[0] = ' ';
		strcat(res, ch);

		return;
	}

	if (s[index] >= '0' && s[index] <= '9')
	{
		char ch[2] = {0};
		ch[0] = s[index] - '0' + 96;
		strcat(res, ch);
		strcat(tmp, ch);
		transform(s, index + 1, res, tmp, flag);
	}

	if (index < strlen(s) - 1 && s[index] <= '2' && s[index] >= '0' && s[index + 1] <= '6' && s[index + 1] >= '0')
	{
		flag++;
		char ch[2] = {0};
		ch[0] = (s[index] - '0') * 10 + (s[index + 1] - '0') + 96;
		if (flag <= 1)
		{
			memset(tmp + index, 0, 128 - index);
		}
		else
		{
			memset(tmp + index - flag + 1, 0, 127 + flag - index);
		}

		strcat(res, tmp);
		strcat(res, ch);
		strcat(tmp, ch);
		transform(s, index + 2, res, tmp, flag);
	}
}

int main()
{
	char str[128] = {0};
	char res[1024] = {0};
	char tmp[128] = {0};

	scanf("%s", str);
	transform(str, 0, res, tmp, 0);
	printf("%s\n", res);

	return 0;
}

更多文章、视频、嵌入式学习资料,微信关注 【学益得智能硬件】

在这里插入图片描述

发布了21 篇原创文章 · 获赞 47 · 访问量 9234

猜你喜欢

转载自blog.csdn.net/xiaopengX6/article/details/104711773