Friday, May 8, 2015

Solution to Reverse Words

This is one solution to "Reverse Words" problem in google codejam hosted at https://code.google.com/codejam/contest/351101/dashboard#s=p1

import java.io.BufferedReader;
import java.io.FileReader;

/**
 * @author: Aniruddha Dutta Chowdhury (adchowdhury@gmail.com)
 * @since: May 8, 2015
 */

public class ReverseWords {

    public static void main(String[] args) {
        String filePath = "input.txt";
       
        try {
            BufferedReader br = new BufferedReader(new FileReader(filePath));
            String sCurrentLine;
            StringBuffer sb = new StringBuffer();
            int insertIndex = 0;
            char currentChar = '\b';
            while ((sCurrentLine = br.readLine()) != null) {
                //System.out.println(sCurrentLine);
                for(int iCharCounter = 0; iCharCounter < sCurrentLine.length(); iCharCounter++) {
                    currentChar = sCurrentLine.charAt(iCharCounter);
                    if(currentChar == ' ') {
                        insertIndex = 0;
                        sb.insert(insertIndex, currentChar);
                    }else {
                        sb.insert(insertIndex++, currentChar);
                    }
                }
                System.out.println(sb);
                sb = new StringBuffer();
                insertIndex = 0;
            }
        } catch (Throwable a_th) {
            a_th.printStackTrace();
        }
    }
}

No comments:

Post a Comment