-
[Java][백준 9093: 단어 뒤집기]아가개발자/자료구조,알고리즘 2021. 7. 29. 16:28
https://www.acmicpc.net/problem/9093
문제
문장이 주어졌을 때, 단어를 모두 뒤집어서 출력하는 프로그램을 작성하시오. 단, 단어의 순서는 바꿀 수 없다. 단어는 영어 알파벳으로만 이루어져 있다.
입력
첫째 줄에 테스트 케이스의 개수 T가 주어진다. 각 테스트 케이스는 한 줄로 이루어져 있으며, 문장이 하나 주어진다. 단어의 길이는 최대 20, 문장의 길이는 최대 1000이다. 단어와 단어 사이에는 공백이 하나 있다.
출력
각 테스트 케이스에 대해서, 입력으로 주어진 문장의 단어를 모두 뒤집어 출력한다.
Insight
문제에서 요구하는 사항은 단어마다 끊어서 단어를 뒤집어 출력하는 것이다.
여기서 눈 여겨 볼 점은 각 단어마다 알파벳을 입력 받은 순서의 반대로 출력해야 하는 후입선출 방식이다.
각 단어가 시작 될 때 스택에 자료를 push해주고 다음 단어가 시작 될 때 pop하여 스택에 저장했던 자료를 꺼내어 출력하도록 코드를 작성해보자.
<Process>
문자열을 입력 받음 -> 문자열의 크기만큼 반복 -> 공백/개행문자가 나올 때까지 스택에 push -> 공백/개행문자가 나오면 pop을 통해서 스택을 비워줌import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.IOException; import java.util.Stack; public class Main { public static int[] arr = null; public static int size=0; public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); int N = Integer.parseInt(br.readLine()); while(N-- >0){ String str = br.readLine(); bw.write(Flip(str)); } bw.flush(); bw.close(); } public static String Flip(String input){ Stack<String> stack = new Stack<>(); input+="\n"; int len = input.length(); String[] str = input.split(""); StringBuilder output = new StringBuilder(); for(int i=0; i<len; i++){ if(str[i].equals(" ")|| str[i].equals("\n")){ while(!stack.empty()){ output.append(stack.pop()); } output.append(str[i]); } else { stack.push(str[i]); } } return output.toString(); } }
'아가개발자 > 자료구조,알고리즘' 카테고리의 다른 글
[Java][백준 17413: 단어 뒤집기 2] (0) 2021.08.01 [Java][백준 1406: 에디터] (0) 2021.07.31 [Java][백준 1874: 스택수열] (0) 2021.07.30 [Java][백준 9012: 괄호] (0) 2021.07.29 [Java] Stack 스택 구현/ Stack class 사용법 (0) 2021.07.28