描述:
对于一个长度为 n 字符串,我们需要对它做一些变形。首先这个字符串中包含着一些空格,就像"Hello World"一样,然后我们要做的是把这个字符串中由空格隔开的单词反序,同时反转每个字符的大小写。比如"Hello World"变形后就变成了"wORLD hELLO"。数据范围: 1≤n≤10^6 , 字符串中包括大写英文字母、小写英文字母、空格。进阶:空间复杂度 O(n) , 时间复杂度 O(n)
输入:
给定一个字符串 s 以及它的长度 n(1 ≤ n ≤ 10^6)
输出:
请返回变形后的字符串。题目保证给定的字符串均由大小写字母和空格构成。
输入样例
This is a sample
16
输出样例
SAMPLE A IS tHIS
Code1:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 1000000
void Transform(char *input,int length);
void Copy(char *input,char *string,int i,int j);
void Copy(char *input,char *string,int i,int j)
{
int temp;
if(!i)
{
j--;
}
else
{
j--;
i++;
}
for(temp=0;i<=j;temp++,i++)
{
string[temp]=input[i];
}
string[temp]='\0';
}
void Transform(char *input,int length)
{
int i,j,k;
i=j=0;
char *a,*b;
do
{
i++;
}while(input[i]!=' '&&input[i]!='\0');
if(input[i]=='\0')
{
goto A;
}
j=i;
while(j<=length)
{
do
{
j++;
}while(input[j]!=' '&&input[j]!='\0');
a=(char *)malloc(i*sizeof(char));
b=(char *)malloc(j*sizeof(char));
Copy(input,a,0,i);
Copy(input,b,i,j);
strcat(b," ");
strcat(b,a);
for(k=0;k<=j-1;k++)
{
input[k]=b[k];
}
i=j;
if(input[j]=='\0')
{
break;
}
}
A: for(i=0;i<=length;i++)
{
if(input[i]>='A'&&input[i]<='Z')
{
input[i]+=32;
}
else if(input[i]>='a'&&input[i]<='z')
{
input[i]-=32;
}
}
}
int main()
{
char *input;
int length;
input=(char *) malloc(MAX*sizeof (char));
gets(input);
scanf("%d",&length);
Transform(input,length);
printf("%s",input);
return 0;
}
Code2:
#include <stdio.h>
#include <stdlib.h>
#define STACK_INIT_SIZE 1000000
typedef char ElemType;
typedef struct
{
char *top;
char *base;
int Stacksize;
}sqStack;
void InitStack(sqStack *s)
{
s->base=malloc(STACK_INIT_SIZE*sizeof(char));
if(!s->base)
{
exit(0);
}
s->Stacksize=STACK_INIT_SIZE;
s->top=s->base;
}
void Push(sqStack *s,char ch)
{
if(s->top-s->base==STACK_INIT_SIZE)
{
exit(0);
}
if(ch>='a'&&ch<='z')
{
ch-=32;
}
else if(ch>='A'&&ch<='Z')
{
ch+=32;
}
*s->top++=ch;
}
void PrintAll(sqStack *s)
{
while(s->top!=s->base)
{
printf("%c",*--s->top);
}
}
int main()
{
int fake,i=0;
char *temp,ch;
sqStack s;
InitStack(&s);
temp=NULL;
while(1)
{
temp=(char *)malloc(100*sizeof(char));
while((ch=getchar())!=' '&&ch!='\n')
{
temp[i++]=ch;
}
temp[i]='\0';
while(i>0)
{
Push(&s,temp[--i]);
}
if(ch=='\n')
{
free(temp);
break;
}
Push(&s,' ');
free(temp);
}
scanf("%d",&fake);
PrintAll(&s);
return 0;
}