성능 요약
메모리: 46544 KB, 시간: 628 ms
분류
구현, 문자열
제출 일자
2023년 10월 12일 15:48:05
문제 설명
문장이 주어졌을 때, 단어를 모두 뒤집어서 출력하는 프로그램을 작성하시오. 단, 단어의 순서는 바꿀 수 없다. 단어는 영어 알파벳으로만 이루어져 있다.
입력
첫째 줄에 테스트 케이스의 개수 T가 주어진다. 각 테스트 케이스는 한 줄로 이루어져 있으며, 문장이 하나 주어진다. 단어의 길이는 최대 20, 문장의 길이는 최대 1000이다. 단어와 단어 사이에는 공백이 하나 있다.
출력
각 테스트 케이스에 대해서, 입력으로 주어진 문장의 단어를 모두 뒤집어 출력한다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main{
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
String[] arr = new String[n];
for(int i = 0; i < n; i++){
StringBuilder sb = new StringBuilder();
String line = br.readLine();
for(String str : line.split(" ")){
StringBuilder tmp = new StringBuilder(str);
sb.append(tmp.reverse()).append(" ");
}
arr[i] = sb.toString();
}
for(String str : arr){
System.out.println(str);
}
}
}
Stack을 활용한 풀이
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;
public class Main{
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
Stack<Character> stack = new Stack<>();
String[] arr = new String[n];
for(int i = 0; i < n; i++){
StringBuilder sb = new StringBuilder();
String line = br.readLine();
for(char ch : line.toCharArray()){
if(ch == ' '){
while(!stack.isEmpty()){
sb.append(stack.pop());
}
sb.append(' ');
}else{
stack.push(ch);
}
}
while(!stack.isEmpty()){
sb.append(stack.pop());
}
arr[i] = sb.toString();
}
for(String str : arr){
System.out.println(str);
}
}
}