2014软件工程夏令营上机考试 C:单词翻转
-
总时间限制:
- 1000ms 内存限制:
- 65536kB
-
描述
-
输入一个句子(一行),将句子中的每一个单词翻转后输出
输入
- 只有一行,为一个字符串,不超过500个字符。单词之间以空格隔开。 输出
- 翻转每一个单词后的字符串 样例输入
-
hello world
样例输出
-
olleh dlrow
#include <iostream>
#include <stack>
#include <cstdio>
#include <cstring>
using namespace std;
int main(){
char s[501];
gets(s);
stack<char>p;
int i = -1;
while(++i < strlen(s)){
if(s[i]!=' '){
p.push(s[i]);
}else {
while(!p.empty()){
cout<<p.top();
p.pop();
}
cout<<" ";
}
}
while(!p.empty()){
cout << p.top();
p.pop();
}
cout << endl;
return 0;
}
参考代码(2):
#include<iostream>
#include<stack>
#include<cstdio>
using namespace std;
int main(){
char s[501];
gets(s);
stack<char>p;
int i=0;
while(true){
if(s[i]=='\0'){
while(!p.empty()){
cout<<p.top();
p.pop();
}
break;
}if(s[i]!=' '){
p.push(s[i]);
i++;
}
else {
while(!p.empty()){
cout<<p.top();
p.pop();
}
cout<<" ";
i++;
}
}
return 0;
}