2014北大軟工夏令營機試 C:單詞翻轉

2014軟件工程夏令營上機考試 C:單詞翻轉


總時間限制: 
1000ms 
內存限制: 
65536kB
描述

輸入一個句子(一行),將句子中的每一個單詞翻轉後輸出

輸入
只有一行,爲一個字符串,不超過500個字符。單詞之間以空格隔開。
輸出
翻轉每一個單詞後的字符串
樣例輸入
hello world
樣例輸出
olleh dlrow

參考代碼(1):
#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;
}


發佈了30 篇原創文章 · 獲贊 4 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章