Tuesday, December 24, 2013

Google Code Jam Notes - Reverse Words - Java

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

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
Analysis:
Straightforward, use String.split("\\s") to separate each word.
Time complexity: O(n).

My solution: (Your opinion is highly appreciated)


[java] view plaincopy
  1. package codeJam.google.com;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.FileReader;  
  5. import java.io.FileWriter;  
  6. import java.io.IOException;  
  7.   
  8. /** 
  9.  * @author Zhenyi 2013 Dec 22, 2013 12:04:12 PM 
  10.  */  
  11. public class ReverseWords {  
  12.     public static void main(String[] args) throws IOException {  
  13.         BufferedReader in = new BufferedReader(new FileReader(  
  14.                 "C:/Users/Zhenyi/Downloads/B-small-practice.in"));  
  15.         FileWriter out = new FileWriter(  
  16.                 "C:/Users/Zhenyi/Downloads/B-small-practice.out");  
  17.         // BufferedReader in = new BufferedReader(new  
  18.         // FileReader("C:/Users/Zhenyi/Downloads/B-large-practice.in"));  
  19.         // FileWriter out = new  
  20.         // FileWriter("C:/Users/Zhenyi/Downloads/B-large-practice.out");  
  21.   
  22.         int N = new Integer(in.readLine());  
  23.   
  24.         for (int cases = 1; cases <= N; cases++) {  
  25.             String[] st = new String(in.readLine()).split("\\s");  
  26.   
  27.             out.write("Case #" + cases + ": ");  
  28.             for (int i = st.length - 1; i >= 0; i--) {  
  29.                 out.write(st[i] + " ");  
  30.             }  
  31.             out.write(" ");  
  32.   
  33.         }  
  34.         in.close();  
  35.         out.flush();  
  36.         out.close();  
  37.     }  
  38. }  

No comments:

Post a Comment