字符串改造(串)
时间: 1ms 内存:128M
描述:
一个字符串,存放在一个数组中,编程序将其改造之后输出:
(1)将S的所有第偶数个字符按照从大到小的次序放在S的后半部分;
(2)将S的所有第奇数个字符按照从小到大的次序放在S的前半部分;
输入:
输入一个字符串
输出:
输出改造后的字符串
示例输入:
ABCDEFGHIJKL
示例输出:
ACEGIKLJHFDB
提示:
参考答案(内存最优[752]):
#include<stdio.h>
#include<malloc.h>
#include<string.h>
#define SEN 1000
struct sqstack
{
char *base;
char *top;
int size;
};
struct sqstack *initEmptyStack()
{
struct sqstack *p;
p=(struct sqstack *)malloc(sizeof(struct sqstack));
if(p!=NULL)
{
p->base=(char *)malloc(sizeof(struct sqstack)*SEN);
if(p->base!=NULL)
{
p->top=p->base;
p->size=SEN;
return p;
}
}
else
free(p);
return NULL;
}
int push(struct sqstack *p,int a)
{
*p->top++=a;
return 0;
}
char gettop(struct sqstack *p)
{
if(p->base!=p->top)
return *(p->top-1);
return 0;
}
char pop(struct sqstack *p)
{
return *(--p->top);
}
int main()
{
char m,a,max,min;
int t1=0,t2=0,t=0,t3;
struct sqstack *p1,*p2,*p3;
p1=initEmptyStack();
p2=initEmptyStack();
p3=initEmptyStack();
while(scanf("%c",&m)!=EOF)
{
t++;
if(t%2==0)
{
push(p1,m);
t1++;
}
else
{
push(p2,m);
t2++;
}
}
while(t2--)
{
t3=0;
min=gettop(p2);
{
while(p2->base!=p2->top)
{
a=pop(p2);
if(a<min)
min=a;
push(p3,a);
}
while(p3->base!=p3->top)
{
a=pop(p3);
if(a==min)
{
t3++;
}
else
push(p2,a);
}
while(t3--)
printf("%c",min);
}
}
while(t1--)
{
t3=0;
max=gettop(p1);
{
while(p1->base!=p1->top)
{
a=pop(p1);
if(a>max)
max=a;
push(p3,a);
}
while(p3->base!=p3->top)
{
a=pop(p3);
if(a==max)
{
t3++;
}
else
push(p1,a);
}
while(t3--)
printf("%c",max);
}
}
printf("\n");
return 0;
}
参考答案(时间最优[0]):
#include<stdio.h>
#include<malloc.h>
#include<string.h>
#define SEN 1000
struct sqstack
{
char *base;
char *top;
int size;
};
struct sqstack *initEmptyStack()
{
struct sqstack *p;
p=(struct sqstack *)malloc(sizeof(struct sqstack));
if(p!=NULL)
{
p->base=(char *)malloc(sizeof(struct sqstack)*SEN);
if(p->base!=NULL)
{
p->top=p->base;
p->size=SEN;
return p;
}
}
else
free(p);
return NULL;
}
int push(struct sqstack *p,int a)
{
*p->top++=a;
return 0;
}
char gettop(struct sqstack *p)
{
if(p->base!=p->top)
return *(p->top-1);
return 0;
}
char pop(struct sqstack *p)
{
return *(--p->top);
}
int main()
{
char m,a,max,min;
int t1=0,t2=0,t=0,t3;
struct sqstack *p1,*p2,*p3;
p1=initEmptyStack();
p2=initEmptyStack();
p3=initEmptyStack();
while(scanf("%c",&m)!=EOF)
{
t++;
if(t%2==0)
{
push(p1,m);
t1++;
}
else
{
push(p2,m);
t2++;
}
}
while(t2--)
{
t3=0;
min=gettop(p2);
{
while(p2->base!=p2->top)
{
a=pop(p2);
if(a<min)
min=a;
push(p3,a);
}
while(p3->base!=p3->top)
{
a=pop(p3);
if(a==min)
{
t3++;
}
else
push(p2,a);
}
while(t3--)
printf("%c",min);
}
}
while(t1--)
{
t3=0;
max=gettop(p1);
{
while(p1->base!=p1->top)
{
a=pop(p1);
if(a>max)
max=a;
push(p3,a);
}
while(p3->base!=p3->top)
{
a=pop(p3);
if(a==max)
{
t3++;
}
else
push(p1,a);
}
while(t3--)
printf("%c",max);
}
}
printf("\n");
return 0;
}
题目和答案均来自于互联网,仅供参考,如有问题请联系管理员修改或删除。