백준 9093번 단어뒤집기 Word Reversal

1 minute read

문제

For each list of words, print a line with each word reversed without changing the order of the words. Each word consists of English letters only.

입력

The input consists of T test cases. The number of test cases (T) is given in the first line of the input file. Each test case consists of a single line: each line contains a list of words separated by one space.

출력

For each test case, print the output on one line.

예제

입력 1

2
I am happy today
We want to win the first prize

출력 1

I ma yppah yadot
eW tnaw ot niw eht tsrif ezirp

Answer

Using a stack method,

import java.io.*;
import java.util.Stack;

public class Main {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

        String inputStr;

        int n = Integer.parseInt(br.readLine());

        for (int i = 0; i < n; i++) {
            inputStr = br.readLine();
            Stack<Character> charStack = new Stack<>();

            for (int j = 0; j < inputStr.length(); j++) {
                if (inputStr.charAt(j) == ' ') {
                    while (!charStack.isEmpty()) {
                        bw.write(charStack.pop());
                    }
                    bw.write(" ");
                } else {
                    charStack.add(inputStr.charAt(j));
                }
            }

            while (!charStack.isEmpty()) {
                bw.write(charStack.pop());
            }
            bw.newLine();

        }
        bw.flush();
        bw.close();
    }
}


Reference

The problem is taken from baekjoon

Leave a comment