天天看點

HDU-1062 Text Reverse(STL stack)

question

翻轉字元串,例如輸入"olleh !dlrow",輸出"hello world!"。

Sample Input

3

olleh !dlrow

m’I morf .udh

I ekil .mca

Sample Output

hello world!

I’m from hdu.

I like acm.

code

#include<iostream>
#include<stack>
//Text Reverse 
//思路:把每個單詞的字元壓入棧中,如果一個單詞壓入完畢(遇到空字元),則彈出各個字元,完成翻轉。 
using namespace std;
int main(){
	int n;
	char ch; 
	scanf("%d",&n);
	getchar(); //輸入的n不能放入棧中 
	stack<char>s;
	while(n--){
		while(true){
			ch=getchar();//一次讀入一個字元 
			if(ch==' '||ch=='\n'||ch==EOF){
				while(!s.empty()){
					printf("%c",s.top());//輸出棧頂 
					s.pop();//清楚棧頂 
				}
				if(ch=='\n'||ch==EOF) break;
				printf(" ");
			}else{
				s.push(ch);//入棧 
			}
		}
		printf("\n");
	}
	return 0;
} 
           

繼續閱讀