Friday, May 3, 2013

Google Code Jam - Africa Qualification 2010 - Reverse Words

Problem Links:

Google Code Jam.

Problem:

Problem 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.
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

Input 

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

Solution:

Ad-hoc.

Source Code:


/**
 * 
 */
package com.googlecodejam.yr2010.africa.qualification;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;

/**
 * @author antonio081014
 * @time May 3, 2013, 11:26:59 PM
 */
public class B {
 public static void main(String[] args) throws Exception {
  B main = new B();
  main.run();
  System.exit(0);
 }

 private void run() throws Exception {
  BufferedReader in = new BufferedReader(new FileReader("input.in"));
  PrintWriter out = new PrintWriter(new FileWriter("output.txt"));
  int T = Integer.parseInt(in.readLine());
  for (int t = 1; t <= T; t++) {
   out.write("Case #" + t + ": ");
   String Value = in.readLine();
   out.write(solve(Value) + "\n");
  }
  in.close();
  out.close();
 }

 private String solve(String value) {
  String[] words = value.split("\\s");
  int N = words.length;
  String ret = "";
  for (int i = N - 1; i > 0; i--)
   ret += words[i] + " ";
  ret += words[0];
  return ret;
 }
}

No comments :