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;
}