[알고리즘/백준] #5397 키로거

JudyLia·2022년 2월 8일
0

알고리즘

목록 보기
27/61
post-thumbnail

문제) 창영이는 강산이의 비밀번호를 훔치기 위해서 강산이가 사용하는 컴퓨터에 키로거를 설치했다. 며칠을 기다린 끝에 창영이는 강산이가 비밀번호 창에 입력하는 글자를 얻어냈다.

키로거는 사용자가 키보드를 누른 명령을 모두 기록한다. 따라서, 강산이가 비밀번호를 입력할 때, 화살표나 백스페이스를 입력해도 정확한 비밀번호를 알아낼 수 있다.

강산이가 비밀번호 창에서 입력한 키가 주어졌을 때, 강산이의 비밀번호를 알아내는 프로그램을 작성하시오. 강산이는 키보드로 입력한 키는 알파벳 대문자, 소문자, 숫자, 백스페이스, 화살표이다.

  • stack 사용(정답코드)
package algorithm_study.day0209;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;

//제출 정답 코드

public class Main2 {
	public static void main(String[] args) throws NumberFormatException, IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb = new StringBuilder();
		int test_case = Integer.parseInt(br.readLine());
		
		for(int t=1;t<=test_case;t++) {
			String[] s = br.readLine().split("");
			Stack<String> stack1 = new Stack<String>();
			Stack<String> stack2 = new Stack<String>();
			
			for(int i=0;i<s.length;i++) {
				switch (s[i]) {
				case "<":
					if(!stack1.isEmpty()) stack2.push(stack1.pop());
					break;
				case ">":
					if(!stack2.isEmpty()) stack1.push(stack2.pop());
					break;
				case "-":
					if(!stack1.isEmpty()) stack1.pop();
					break;

				default:
					stack1.push(s[i]);
					break;
				}
			}
			
			while(!stack2.isEmpty()) {
				stack1.push(stack2.pop());
			}
			
			for(int i=0;i<stack1.size();i++) {
				sb.append(stack1.elementAt(i));
			}
			sb.append("\n");
		}
		System.out.println(sb.toString());
	}
}
  • linkedlist 사용(시간초과)
package algorithm_study.day0209;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.List;

//LinkedList를 사용(시간초과)

public class Main {
	public static void main(String[] args) throws NumberFormatException, IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		
		int test_case = Integer.parseInt(br.readLine());
		
		for(int t=1;t<=test_case;t++) {
			String[] s = br.readLine().split("");
			List<String> list = new LinkedList<String>();
			StringBuilder sb = new StringBuilder(s.length);
			int idx=0;
			for(int i=0;i<s.length;i++) {
				
				switch (s[i]) {
				case "<":
					if(!list.isEmpty()&&idx>0) {
						idx--;
					}
					break;
				case ">":
					if(!list.isEmpty()&&idx<list.size()) {
						idx++;
					}
					break;
				case "-":
					if(!list.isEmpty()&&idx>0) {
						list.remove(--idx);
						
					}
					break;

				default:
					list.add(idx++, s[i]);
					break;
				}
			}
			
			int size=list.size();
			for(int i=0;i<size;i++) {
				sb.append(list.get(i));
			}
			sb.append("\n");
			System.out.print(sb.toString());
		}
	}
}
profile
안녕:)

0개의 댓글

관련 채용 정보