Algorithm/Baekjoon
[백준저지] 9093번 : 단어 뒤집기
wavid
2020. 9. 29. 10:35
9093번: 단어 뒤집기
첫째 줄에 테스트 케이스의 개수 T가 주어진다. 각 테스트 케이스는 한 줄로 이루어져 있으며, 문장이 하나 주어진다. 단어의 길이는 최대 20, 문장의 길이는 최대 1000이다. 단어와 단어 사이에는
www.acmicpc.net
1. 문제
입력 받은 문장의 각 단어들을 뒤집어주는 문제
입)
I am happy today
We want to win the first prize
출)
I ma yppah yadot
eW tnaw ot niw eht tsrif ezirp
2. 풀이
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(bf.readLine());
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
while (t-- > 0) {
String str = bf.readLine() + "\n";
Stack<Character> s = new Stack<>();
for (char ch : str.toCharArray()) {
if (ch == '\n' || ch == ' ') {
while (!s.isEmpty()) {
bw.write(s.pop());
}
bw.write(ch);
} else {
s.push(ch);
}
}
}
bw.flush();
}
}
문장을 입력받고, 문장의 끝을 표시하기 위해 '\n' 문자를 추가함.
스택에 문자를 push하다가, '\n' 문자나 ' '(공백) 문자를 만나면 모두 pop해준다.