Cooper's devlog

단어 뒤집기 : 9093번 - JAVA 본문

Algorithm/Baekjoon

단어 뒤집기 : 9093번 - JAVA

cooper_dev 2020. 7. 6. 01:05

1. 문제링크

https://www.acmicpc.net/problem/9093

 

9093번: 단어 뒤집기

문제 문장이 주어졌을 때, 단어를 모두 뒤집어서 출력하는 프로그램을 작성하시오. 단, 단어의 순서는 바꿀 수 없다. 단어는 영어 알파벳으로만 이루어져 있다. 입력 첫째 줄에 테스트 케이스의

www.acmicpc.net


2. 문제 설명


3. 문제 접근법

-stack의 FILO(First In Last Out)특성을 이용한 문제풀이 :

(stack에서 push한 후, pop하는 단어는 거꾸로 출력된다!! : FILO의 특성이용!!)

1. 문자열을 char[](toCharArray)로 변환

1. char가 ' '가 아니라면(알파벳일 때), stack.push()를 한다.

2. char가 ' '라면, stack을 비울때 까지, stack.pop()을 한다.

 

 


4. 문제 풀이

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
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;
 
public class word_reverse {
    public static void main(String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int test_case = Integer.parseInt(br.readLine());
        
        for (int test_num = 1; test_num <= test_case; test_num++) {
            Stack<Character> stack = new Stack<>();
            String str = br.readLine();
            str += ' ';
          
            for (int index = 0; index < str.length(); index++) {
                if(str.charAt(index) == ' ') {
                    while(!stack.isEmpty()) {
                        System.out.print(stack.pop());
                    }
                    System.out.print(" ");
                }else {
                    stack.add(str.charAt(index));
                }
            }
            System.out.println();
        }
        br.close();
    }
}
 
//1.string에 결과값을 추가하여 넣는 방법을 사용할 시, 메모리 초과 현항이 발생했다.
// -> System.out.print로 출력해서 '메모리 초과' 문제 해결.
 

 

 

 

<정답확인>


5. 개선점 또는 트러블 슈팅

- 마지막 단어를 출력받기 위해 처음에 ' '(빈칸)을 사용하는 것에서 시간이 걸림

-while문 작성 시, 순간 감이 안잡혀서 시간 잡아먹음

 

 

'Algorithm > Baekjoon' 카테고리의 다른 글

조세퍼스 문제 : 1158번 - JAVA  (0) 2020.07.08
에디터:1406번 - JAVA  (0) 2020.07.08
스택수열 : 1874번 - JAVA  (0) 2020.07.07
괄호 : 9012번 - JAVA  (0) 2020.07.07
스택 : 10828번 - JAVA  (0) 2020.07.06
Comments