본문 바로가기

Algorithm

[ 백준 / 1406 ] 에디터 ( 자바 )

반응형

www.acmicpc.net/problem/1406

 

1406번: 에디터

첫째 줄에는 초기에 편집기에 입력되어 있는 문자열이 주어진다. 이 문자열은 길이가 N이고, 영어 소문자로만 이루어져 있으며, 길이는 100,000을 넘지 않는다. 둘째 줄에는 입력할 명령어의 개수

www.acmicpc.net

 

 

에디터 문제를 처음보고 구현으로 생각했다. 그래서 케이스를 나눠서 substring을 이용했다. 커서의 위치는 index를 이용하였다. 하지만 그렇게 문제를 풀면 시간초과가 났다.

 

package bj;

import java.util.*;
import java.io.*;
public class Main {

	

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String line = br.readLine();
		int N = Integer.parseInt(br.readLine());
		String[] array = new String[N];
		int index = line.length();
		
		for(int i=0;i<N;i++) {
			array[i] = br.readLine();
		}
		
		for(int i=0;i<N;i++) {
			String inputLine = array[i];
			
			if(inputLine.length()==3) {
				char c = inputLine.charAt(2);
				line = line.substring(0,index) + c + line.substring(index,line.length());
				index += 1;
			} else {
				if(inputLine.equals("L")) {
					if(index==0) continue;
					index -=1;
				}
				
				else if(inputLine.equals("D")) {
					if(index==line.length()) continue;
					index +=1;
				}
				
				else if(inputLine.equals("B")) {
					if(index==0) continue;
					index -= 1;
					line = line.substring(0,index) + line.substring(index+1, line.length());
				}
			}
		}
		
		System.out.println(line);
	}
}

 

알고보니 방법은 stack을 2개 사용하는 것이다. 처음에는 기준문자열을 left라는 stack에 순서대로 담았다. L을 할 경우 left stack을 pop하여 right stack으로 옮겨주고, D를 할 경우 right stack을 pop하여 left stack으로 옮긴다. 또한 B일 경우 left stack을 pop 하였다. P를 통해 추가할 때는, left stack에 add를 한다.

 

마지막으로는 left stack을 순서대로 담고, right stack은 pop하여 거꾸로 담아 합친다.

 

package bj;

import java.util.*;
import java.io.*;
public class Main {

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String line = br.readLine();
		int N = Integer.parseInt(br.readLine());
		String[] array = new String[N];
		int index = line.length();
		
		for(int i=0;i<N;i++) {
			array[i] = br.readLine();
		}
		
		for(int i=0;i<N;i++) {
			String inputLine = array[i];
			
			if(inputLine.length()==3) {
				char c = inputLine.charAt(2);
				line = line.substring(0,index) + c + line.substring(index,line.length());
				index += 1;
			} else {
				if(inputLine.equals("L")) {
					if(index==0) continue;
					index -=1;
				}
				
				else if(inputLine.equals("D")) {
					if(index==line.length()) continue;
					index +=1;
				}
				
				else if(inputLine.equals("B")) {
					if(index==0) continue;
					index -= 1;
					line = line.substring(0,index) + line.substring(index+1, line.length());
				}
			}
		}
		
		System.out.println(line);
	}
}

 

반응형