ACM 字符串综合一

来源:互联网 发布:vb进度条控件使用 编辑:程序博客网 时间:2024/05/22 14:11

原题链接:

         http://newoj.acmclub.cn/problems/1784

题目描述:

      将一句话中的单词次序倒置,每两个单词之间由一个空格隔开,但是不改变单词中字母的顺序,输出改变后的句子。

输入:

      多组输入输出。每一行需要改变的话。(句中只包含大小写英文字母及空格)

输出:

      与输入相对应输出改变后的句子

样例输入

         who are you

         Welcome to Northeast university of Qinhuangdao

样例输出

          you are who

           Qinhuangdao of university Northeast to Welcome

解题思路:

          刚开始想的是使用使用堆栈存储数据,然后依次取顶部元素,这样就将整个字符串的顺序给改变了,并将改变顺序的字符串存到数组中,然后开始检测是否有空格,如果有空格的话,就从这一个空格开始的位置到前一个空格的位置依次输出,最后一步就是从数组的最后位置开始输出一直到最后一个空格。但是判题系统给出的错误的

         使用数组存储,编写一个函数专门用来改变字符数组的顺序,首先将整个数组的顺序改变,然后检测空格,改变每个单词的顺序

错误代码:

            

#include <bits/stdc++.h>using namespace std;int main(){while(true){stack <char> s1;char data[1024];char a; int k=0,pos=-1; while((a=cin.get()) != '\n')    s1.push(a);  while(!s1.empty()){  data[k++] = s1.top();  s1.pop();  if(data[k-1] == ' '){  for(int j=k-2;j > pos;j--)   cout<<data[j];   pos=k-1;   cout<<' ';}  }  //cout<<k<<endl;  for(int j=k-1;j>pos;j--)   cout<<data[j];   cout<<endl;  //  cout<<k<<" "<<pos<<endl;}return 0;}
满分代码:

#include <bits/stdc++.h>using namespace std;void change(char *a,int begin,int end){int i,j;for(i=begin,j=end;i<j;i++,j--)swap(a[i],a[j]);//return a; }int main(){char a[1024];int j=0;while(gets(a)){int len=strlen(a),pos=-1;change(a,0,len-1);for(int i=0;i<len;i++){if(a[i] == ' '){change(a,pos+1,i-1);pos=i;}}change(a,pos+1,len-1);    for(int i=0;i<len;i++)     cout<<a[i];     cout<<endl;}/*while((a[j++]=cin.get()) != '\n');//cout<<j<<endl;change(a,0,j-2);for(int i=0;i<j-1;i++) cout<<a[i];*/return 0;}


原创粉丝点击