Question (in Chinese): http://ac.jobdu.com/problem.php?pid=1361
Question Name: Reverse Words In Sentence
Question Description: given a string, reverse the words’ order.
Input: the input might contain multiple test cases. Each line, as a whole string, is a test case.
Output: print the reversed string.
1 2 3 4 5 6 | Input: student. a am I I'm a Freshman and I like JOBDU! Output: I am a student. JOBDU! like I and Freshman a I'm |
It seems, there is not accepted Java solution. The OJ system always says “Presentation Error”.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 | /*---------------------------------------------------------------- * Author: Sheng Yu - codesays.com * Written: 09/09/2014 * Last updated: 09/09/2014 * * Filename: ReverseWordsInSentence.java * Compilation: javac ReverseWordsInSentence.java * Execution: java ReverseWordsInSentence * JDK Used: 1.7 *----------------------------------------------------------------*/ import java.util.Scanner; /** * The utility to reverse words in sentence. * @author Sheng Yu codesays.com */ public class ReverseWordsInSentence { /** * Reverse the input[begin : end], both index inclusive. * @param input the char array to reverse. * @param begin the begin position of the to-reverse sub-array. * @param end the end position of the to-reverse sub-array. */ private static void reverseArray(char[] input, int begin, int end) { int beginPos = begin, endPos = end; char temp; while (beginPos < endPos) { temp = input[beginPos]; input[beginPos++] = input[endPos]; input[endPos--] = temp; } return; } /** * Reverse all words in the given sentence. * @param input the original string * @return the new string, in which all words are reversed. */ public static String reversWords(String input) { char[] inputChars = input.toCharArray(); int begin, end; // Reverse the whole string. reverseArray(inputChars, 0, inputChars.length - 1); // Reverse each word (non-space consecutive letters) begin = 0; end = -1; while (++end < inputChars.length) { if (inputChars[end] == ' ') { // Reverse the current word reverseArray(inputChars, begin, end - 1); // Prepare for the next word begin = end + 1; } } if (begin != inputChars.length) { // The last word remains for process. reverseArray(inputChars, begin, end - 1); } return new String(inputChars); } /** * Stub for test. * @param args the command line arguments. * @throws IOException when input gets error. */ public static void main(String[] args) { Scanner sin = new Scanner(System.in); String input = null; while (sin.hasNextLine()) { input = sin.nextLine(); System.out.println(reversWords(input)); } } } |