Google Code jam Solutions: Problem B. Reverse Words


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.


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.


For each test case, output one line containing “Case #x: ” followed by the list of words in reverse order.


Small dataset

N = 5
1 ≤ L ≤ 25

Large dataset

N = 100
1 ≤ L ≤ 1000


Input Output
this is a test
all your base
Case #1: test a is this
Case #2: foobar
Case #3: base your all

C++ Solution:

    Author      :   Sreejith Sreekantan
    Description :   Problem B. Reverse Words


using namespace std;

int main(int argc, char const *argv[])
    int numOfTestInstances;
    cin >> numOfTestInstances;
    for (int testInstanceNum = 0; testInstanceNum < numOfTestInstances; ++testInstanceNum)
        istringstream in;
        string s;
        cin >> ws;
        getline(cin ,s);
        replace(s.begin(), s.end(), ' ', '\n');
        stack stack_s_rev;

        while (in >> s)
        cout << "case #" << testInstanceNum+1 << ": ";
            cout << << " ";
        cout << endl;

    return 0;

Published by


A strong believer of: 1. Knowledge is power 2. Progress comes from proper application of knowledge 3. Reverent attains wisdom 4. For one's own salvation, and for the welfare of the world

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s