-
[Java] BOJ 1406 에디터개발자 취업/코딩테스트 준비 2023. 4. 25. 19:58반응형
1406번: 에디터
첫째 줄에는 초기에 편집기에 입력되어 있는 문자열이 주어진다. 이 문자열은 길이가 N이고, 영어 소문자로만 이루어져 있으며, 길이는 100,000을 넘지 않는다. 둘째 줄에는 입력할 명령어의 개수
www.acmicpc.net
오답 코드
- 삽입/삭제가 자주 일어나는 문제라 ArrayList가 아니라 LinkedList를 선택함
- 하지만 가장 마지막에 add하는 경우에서 100,000(최초 입력 길이) * 500,000(명령어 수)로 인해 시간 초과 발생
import java.io.*; import java.util.*; public class Main { static BufferedReader br; static BufferedWriter bw; static StringTokenizer st; static String str; static int N, pos; static LinkedList<Character> list; public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); bw = new BufferedWriter(new OutputStreamWriter(System.out)); str = br.readLine(); N = Integer.parseInt(br.readLine()); list = new LinkedList<>(); for (int i = 0; i < str.length(); i++) { list.add(str.charAt(i)); } pos = str.length(); for (int i = 0; i < N; i++) { str = br.readLine(); char c = str.charAt(0); if (c == 'L') { if (pos > 0) { pos--; } } else if (c == 'D') { if (pos < list.size()) { pos++; } } else if (c == 'B') { if (pos > 0) { list.remove(--pos); } } else { char alph = str.charAt(2); list.add(pos++, alph); } } for (char c : list) { bw.write(c); } bw.flush(); } }
정답 코드
- 커서 위치에 따라 2개의 스택을 활용하여 구현
- 커서 왼쪽 stack1 / 커서 오른쪽 stack에 저장
- 마지막엔 stack1을 stack2에 옮겼다가 출력
import java.io.*; import java.util.*; public class Main { static BufferedReader br; static BufferedWriter bw; static StringTokenizer st; static String str; static int N, pos; static Stack<Character> stack1, stack2; public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); bw = new BufferedWriter(new OutputStreamWriter(System.out)); str = br.readLine(); N = Integer.parseInt(br.readLine()); stack1 = new Stack<>(); stack2 = new Stack<>(); for (int i = 0; i < str.length(); i++) { stack1.push(str.charAt(i)); } pos = str.length(); for (int i = 0; i < N; i++) { str = br.readLine(); char c = str.charAt(0); if (c == 'L') { if (!stack1.isEmpty()) { stack2.push(stack1.pop()); } } else if (c == 'D') { if (!stack2.isEmpty()) { stack1.push(stack2.pop()); } } else if (c == 'B') { if (!stack1.isEmpty()) { stack1.pop(); } } else { char alph = str.charAt(2); stack1.push(alph); } } while (!stack1.isEmpty()) { stack2.push(stack1.pop()); } while (!stack2.isEmpty()) { bw.write(stack2.pop()); } bw.flush(); } }
'개발자 취업 > 코딩테스트 준비' 카테고리의 다른 글
[Java] BOJ 14888 연산자 끼워넣기 (0) 2023.05.01 [Java] BOJ 2217 로프 (0) 2023.04.28 [Java] BOJ 1986 체스 (1) 2023.04.27 [Java] BOJ 1522 문자열 교환 (0) 2023.04.26 [Java] BOJ 14426 접두사 찾기 (1) 2023.04.25