https://www.acmicpc.net/problem/5430
5430번: AC
각 테스트 케이스에 대해서, 입력으로 주어진 정수 배열에 함수를 수행한 결과를 출력한다. 만약, 에러가 발생한 경우에는 error를 출력한다.
www.acmicpc.net
저는 해당 문제를 구현을 통해서 문제를 해결하였습니다.
저는 특이하게 배열의 순서를 변경할 때, 배열의 순서를 역순으로 변경하지 않고, 맨 앞의 인덱스와 끝의 인덱스를 추적하였고, 현재 방향에 따라 앞의 인덱스나 끝의 인덱스를 늘리거나 줄였습니다.
package BOJ.etc;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.function.Function;
public class BOJ_5430 {
private static final Function<String,Integer> stoi = Integer::parseInt;
private static final String ERROR = "error";
private static final char R = 'R';
private static final char D = 'D';
private static final String SEPARATOR = ",";
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int testCnt = stoi.apply(br.readLine());
for(int t = 0 ; t < testCnt ; t++){
String command = br.readLine();
int n = stoi.apply(br.readLine());
String arrStr = br.readLine();
int[] arr = detectArr(arrStr,n);
cal(arr,n,command);
}
}
private static void cal(int[] arr, int n, String command) {
int dCnt = 0;
for(int i = 0 ; i < command.length(); i++){
if(command.charAt(i) == D){
dCnt++;
}
}
if(dCnt > n){
System.out.println(ERROR);
return;
}
int startIndex = 0;
int endIndex = n-1;
boolean forwardDir = true;
for(int i = 0 ; i < command.length(); i++){
if(command.charAt(i) == R){
forwardDir = !forwardDir;
}else{ // D
if(forwardDir){
startIndex++;
}else{
endIndex--;
}
}
}
printArr(arr,startIndex,endIndex,forwardDir);
}
private static void printArr(int[] arr, int startIndex, int endIndex,boolean forwardDir) {
StringBuilder sb = new StringBuilder();
sb.append("[");
if(forwardDir){
for(int i = startIndex ; i <= endIndex ; i++){
sb.append(arr[i]+SEPARATOR);
}
}else{
for(int i = endIndex ; i >= startIndex ; i--){
sb.append(arr[i]+SEPARATOR);
}
}
if(startIndex <= endIndex){ // 빈 배열인 경우를 제외
sb.setLength(sb.length()-1); // 마지막 ',' 지우기
}
sb.append("]");
System.out.println(sb);
}
private static int[] detectArr(String arrStr,int n) {
arrStr = arrStr.substring(1, arrStr.length()-1); // 입력의 '[',']' 제거
int[] result = new int[n];
String[] temp = arrStr.split(SEPARATOR);
for(int i = 0 ; i < n ; i++){
result[i] = stoi.apply(temp[i]);
}
return result;
}
}
'알고리즘' 카테고리의 다른 글
백준 5557번 1학년 (JAVA) (0) | 2022.08.04 |
---|---|
배준 19621번 회의실 배정2 (JAVA) (0) | 2022.08.03 |
백준 13334번 철로 (JAVA) (0) | 2022.08.01 |
백준 14940번 쉬운 최단거리 (JAVA) (0) | 2022.07.31 |
백준 21736번 헌내기는 친구가 필요해 (JAVA) (0) | 2022.07.30 |