打印alpha范围最有效的方法?

时间:2016-10-19 15:03:01

标签: string algorithm

我想创建一个简单的程序:它获取2个字符串作为输入,并输出它们之间的所有内容。例如,对于输入'a','b',输出为:

a b

输入'a','zz',输出为:

a b c ... x y z aa ab ac ... ax ay az ba bb bc ... bx by bz ... za zb zc ... zx zy zz

最有效的方法是什么?

----编辑----

以下是我的实现,首先使用递归:

void rec_print(int current)
{
    if(current == max_len)
    {
        for(char c='a'; c<= 'z'; ++c)
        {
            global[current] = c;
            printf("%s\n", global);

        }
    }
    else
    {
        for(char c='a'; c<= 'z'; ++c)
        {
            global[current] = c;
            rec_print(current+1);
        }
    }
}

然后使用循环:

void loop_print()
{
    char *buffer;
    int i;

    for( int len=1; len<= 5; len++)
    {
        buffer = calloc(len+1, sizeof(char));
        memset(buffer, 'a', len);

        printf("buffer = %s\n", buffer);

        system("pause");

        do
        {
            i=len-1;

            for(char c='a'; c<='z'; ++c)
            {
                buffer[len-1] = c;
                printf("%s\n", buffer);
            }

            while(i > -1 && buffer[i] == 'z')
            {
                buffer[i] = 'a';
                i--;
            }

            buffer[i]++;


        }
        while (i != -1);
    }


}

----编辑2 ----

回答了我的问题

1 个答案:

答案 0 :(得分:0)

这应该是完整算法的丑陋版本:

void loop_print()
{
    char *buffer;
    int i;

    char dst_buffer[5] = "00000";

    for( int len=1; len<= 3; len++)
    {
        buffer = calloc(len+1, sizeof(char));
        memset(buffer, 'a', len);

        if(len == 1)
        {
            strcpy(dst_buffer, "z");
        }
        if ( len == 2)
        {
            strcpy(dst_buffer, "bc");
        }
        if(len == 3)
        {
            strcpy(dst_buffer, "abc");
        }


        // printf("buffer = %s\n", buffer);
        // printf("dstbuf = %s\n", dst_buffer);

        // system("pause");

        do
        {
            i=len-1;

            printf("%s\n", buffer);

            while(i > -1 && buffer[i] == 'z')
            {
                buffer[i] = 'a';
                i--;
            }

            buffer[i]++;


        }
        while (strcmp(buffer, dst_buffer) == -1);

        printf("%s\n", buffer);

    }


}

输出:

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
aa
ab
ac
ad
ae
af
ag
ah
ai
aj
ak
al
am
an
ao
ap
aq
ar
as
at
au
av
aw
ax
ay
az
ba
bb
bc
aaa
aab
aac
aad
aae
aaf
aag
aah
aai
aaj
aak
aal
aam
aan
aao
aap
aaq
aar
aas
aat
aau
aav
aaw
aax
aay
aaz
aba
abb
abc