공부블로그
[백준] 9093번 단어 뒤집기 본문
https://www.acmicpc.net/problem/9093
9093번: 단어 뒤집기
첫째 줄에 테스트 케이스의 개수 T가 주어진다. 각 테스트 케이스는 한 줄로 이루어져 있으며, 문장이 하나 주어진다. 단어의 길이는 최대 20, 문장의 길이는 최대 1000이다. 단어와 단어 사이에는
www.acmicpc.net
Ver.1
Stack과 reverse() 둘 다 사용해서 풀었는데 굳이 그러지 않아도 단어 단위로 stack에 넣거나 reverse()를 사용하면 더 간단한 알고리즘이 가능하다.
import java.util.*;
class Main {
public static void main(String[] args) { // 가변인자(실인자를 배열로 받음. 실인자 개수= 배열길이
Stack<String> st = new Stack<String>();
Scanner scan = new Scanner(System.in);
int t = scan.nextInt();
String[] s = new String[t];
scan.nextLine();
for(int i=0; i<t; i++){
s[i] = scan.nextLine();
}
StringBuilder sb;
for(int i = t-1; i>-1; i--) {
String[] arr = s[i].split(" ");
// arr배열 arr[length-1]부터 arr[0]순서로 stack에 넣는다.
for(int j=arr.length-1; j>-1; j--) {
st.push(new StringBuilder(arr[j]).reverse().toString());
}
if(i != 0)
st.push("\n");
}//for
while(!st.empty()) {
String str = st.pop();
if("\n".equals(str))
System.out.println();
else {
System.out.print(str+" ");
}
}//while
}
}
Ver.2
public void solution2(int t, String ...s) {
Stack<String> stac = new Stack<String>();
for(int i=0; i < t; i++) {
String arr[] = s[i].split(" ");
for(int j=0; j < arr.length; j++) {
System.out.print(new StringBuilder(arr[j]).reverse().toString());
System.out.print(" ");
}System.out.println();
}
}
'IT > 알고리즘' 카테고리의 다른 글
[프로그래머스] 1차 다트게임 (0) | 2022.09.13 |
---|---|
[백준] 9012번 괄호 (0) | 2022.08.24 |
[프로그래머스] 체육복 (0) | 2022.08.18 |
[프로그래머스] 폰켓몬 (0) | 2022.08.15 |
단순 삽입 정렬 (0) | 2022.08.08 |
Comments