1009 說反話 (20 分)
一.題目:
給定一句英語,要求你撰寫程式,將句中所有單詞的順序顛倒輸出,
輸入格式:
測驗輸入包含一個測驗用例,在一行內給出總長度不超過 80 的字串,字串由若干單詞和若干空格組成,其中單詞是由英文字母(大小寫有區分)組成的字串,單詞之間用 1 個空格分開,輸入保證句子末尾沒有多余的空格,
輸出格式:
每個測驗用例的輸出占一行,輸出倒序后的句子,
輸入樣例:
Hello World Here I Come
輸出樣例:
Come I Here World Hello
二.題解:
解法一:
將輸入字串翻轉,再把每個單詞內部翻轉,即可得到輸出
Step1.Hello World Here I Come
Step2.emoC I ereH dlroW olleH
Step3.Come I Here World Hello
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
int main()
{
string s,s1;
while(cin>>s1)
{
s+=' '+s1;
}
//在輸入時,cin遇到空格就停止輸入,所以只能一段一段讀入,最后拼接起來
int len=s.length();
vector<char>str(len);
for(int i=0; i<len; i++)
{
str[i]=s[i];
}
reverse(str.begin(),str.end());//整體翻轉
int tmp=0;
for(int i=0; i<len; i++)
{
if(str[i]==' ')
{
reverse(str.begin()+tmp,str.begin()+i);//單詞內部翻轉
tmp=i+1;
}
}
for(int i=0; i<len-1; i++)//這里注意為了讓i<len-1不輸出最后的‘ ’
{
printf("%c",str[i]);
}
return 0;
}
運行結果
為了讓大家更好看清楚把‘ ’換成了’~’

這里注意while回圈的終止
終止輸入的方式:
windows系統下使用ctrl+Z
linux系統下使用ctrl+D

解法二:
在這里使用了堆疊這個資料結構,堆疊是限定在表的一端進行插入和洗掉的運算的線性表,通常將插入、洗掉的一端稱為堆疊頂,另一端稱為堆疊底,不含元素的空表稱為空堆疊,堆疊的操作具有先進后出或后進先出的特點,

將輸?的每個單詞s都依次壓?堆疊中,然后將堆疊頂元素依次彈出,直到堆疊空為?
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <stack>
using namespace std;
int main()
{
stack<string>str;
string s;
while(cin>>s){
str.push(s);
}
int flag=0;
while(!str.empty()){
if(flag){
cout<<" ";
}
cout<<str.top();
str.pop();
flag=1;
}
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/271342.html
標籤:其他
上一篇:用戶模式和內核模式(執行緒級)
下一篇:時間復雜度的計算
