考虑一个字母到整数的编码系统,其中 'a' 表示为 1,'b' 表示为 2,.. 'z' 表示为 26。给定一个数字数组(1 到 9)作为输入,编写一个函数打印输入数组的所有有效解释。
/*Examples
Input: {1, 1}
Output: ("aa", 'k")
[2 interpretations: aa(1, 1), k(11)]
Input: {1, 2, 1}
Output: ("aba", "au", "la")
[3 interpretations: aba(1,2,1), au(1,21), la(12,1)]
Input: {9, 1, 8}
Output: {"iah", "ir"}
[2 interpretations: iah(9,1,8), ir(9,18)]*/
我的c代码
#include<iostream>
using namespace std;
#include<string.h>
int a[10]={2,3,4,4,2,4,2,8,9};
char c[]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
void func(int i,char result[10])
{
if(i==10)
{
int l=strlen(result);
for(int j=0;j<l;j++)
cout<<result[j];
}
else
{
if(10*a[i]+a[i+1]<26)
{
strcat(result,"c[10*a[i]+a[i+1]]");
func(i+2,result);
}
strcat(result,"c[a[i]]");
func(i+1,result);
}
}
int main()
{
func(0,"");
}
我无法找出错误。你能帮我吗?
最佳答案
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int a[9]={2,3,4,4,2,4,2,8,9};
char c[]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
void func(int i,char result[11])
{
if(i==10)
{
printf ("%s\n", result);
}
else
{
char * temp = (char *)malloc(11);
sprintf(temp, "%s%c", result, c[a[i] - 1]);
func(i+1,temp);
free(temp);
if(i < 9 && 10*a[i]+a[i+1] < 26)
{
char * temp = (char *)malloc(11);
sprintf(temp, "%s%c", result, c[10*a[i]+a[i+1] - 1]);
func(i+2, temp);
free (temp);
}
}
}
int main()
{
func(0,"");
}
输出
bcddbdbhi
bcddxbhi
wddbdbhi
wddxbhi
代码中潜在的致命问题
-
strcat(result,"c[10*a[i]+a[i+1]]");
和strcat(result,"c[a[i]]");
您将这些字符串连接到result
它的大小仅为 10,而不是连接与该数字对应的字符。
其他问题
- 内部
if(10*a[i]+a[i+1]<26)
您正在更改result
的内容,当递归结束时,result的值与进入函数时的值不一样。因此,最好在内部创建新字符串,并在任务结束时释放它们。
建议
- 尽量不要混合使用 C 和 C++ 函数。
关于c++ - 找到数字数组的所有可能的解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18720712/