Problem B. Reverse Words
Problem
Given a list of space separated words, reverse the order of the words. Each line of text contains L
letters and W
words. A line will only consist of letters and space characters. There will be exactly one space character between each pair of consecutive words.
Input
The first line of input gives the number of cases, N.
N test cases follow. For each test case there will a line of letters and space characters indicating a list of space separated words. Spaces will not appear at the start or end of a line.
Output
For each test case, output one line containing "Case #x: " followed by the list of words in reverse order.
Limits
Small dataset
N = 5
1 ≤ L ≤ 25
Large dataset
N = 100
1 ≤ L ≤ 1000
Sample
#include <iostream>
#include <vector>
using namespace std;
#define IN 1
#define OUT 0
class reverseWord {
vector<string> strVector;
size_t loopNum;
vector<vector<string> > wordVector;
public:
void inputStr(){
cin>>loopNum;
getchar(); //getchar() get the '\n' that left in buffer.
//if there is no getchar(),getline() will get the '\n' in buffer and get null string
string str;
size_t count=loopNum;
while (count--) {
getline(cin,str);
strVector.push_back(str);
}
}
void printVector(){
int count=0;
for (vector<vector<string> >::const_iterator it=wordVector.begin();it!=wordVector.end(); ++it) {
cout<<"Case #"<<count++<<": ";
for (vector<string>::const_iterator to=it->begin(); to!=it->end(); ++to) {
cout<<*to<<" ";
}
cout<<endl;
}
}//printVector
void seperate(){
vector<string> tempVector;
for (int t=0; t<loopNum;++t ) {
string str=strVector[t];
size_t length=str.length();
bool state=OUT;
size_t record;
string temp;
for (size_t i=0; i<length; ++i) {
if (str[i]==' '||str[i]=='\n') {
state=OUT;
temp=str.substr(record,i-record);
tempVector.push_back(temp);
}
else if(state==OUT){
state=IN;
record=i;
}
}//for
temp=str.substr(record,length-record);
tempVector.push_back(temp);
wordVector.push_back(tempVector);
tempVector.clear();
}//for
}// seperate end
void reverse(){
//make word in wordVector reverse
for(size_t i=0;i<loopNum;++i){
size_t length=wordVector[i].size();
int begin=0;
while (begin<length) {
string temp;
temp=wordVector[i][begin];
wordVector[i][begin++]=wordVector[i][--length];
wordVector[i][length]=temp;
}
}//for
}//reverse end
};
int main(){
reverseWord test;
// input the string
test.inputStr();
//seperate the string and save it to wordVector
test.seperate();
test.reverse();
test.printVector();
return 0;
}
getchar() get the '\n' that left in buffer.
//if there is no getchar(),getline() will get the '\n' in buffer and get null string