23년 4월 25일 [알고리즘 - 자료구조]

sua·2023년 4월 24일
0

알고리즘 가보자고

목록 보기
7/101

백준 1406번 에디터

문제

링크 : https://www.acmicpc.net/problem/1406

나의 풀이

import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String str = br.readLine();
        int m = Integer.parseInt(br.readLine());

        Stack<Character> lstack = new Stack<>();
        Stack<Character> rstack = new Stack<>();
        for(char c : str.toCharArray()) {
            lstack.push(c);
        }

        for(int i = 0; i < m; i++) {
            String s = br.readLine();
            if(s.contains("L")) {
                if(!lstack.isEmpty()) {
                    rstack.push(lstack.pop());
                }
            } else if(s.contains("D")) {
                if(!rstack.isEmpty()) {
                    lstack.push(rstack.pop());
                }
            } else if(s.contains("B")) {
                if(!lstack.isEmpty()) {
                    lstack.pop();
                }
            } else if(s.contains("P")) {
                String ch = s.split(" ")[1];
                lstack.push(ch.charAt(0));
            }
        }

        while(!lstack.isEmpty()) {
            rstack.push(lstack.pop());
        }

        StringBuilder sb = new StringBuilder();
        while(!rstack.isEmpty()) {
            sb.append(rstack.pop());
        }

        System.out.println(sb);
    }
}

커서 기준 왼쪽에 있는 문자들을 담을 lstack과 커서 기준 오른쪽에 있는 문자들을 담을 rstack 2개의 스택을 생성한다. 그런 다음 명령어를 입력 받기 전에 있던 문자들은 모두 lstack에 push 해준다. for문을 돌면서 명령어를 받고 명령어에 L이 포함되는 경우 커서가 왼쪽으로 한 칸 옮겨지는 것이므로 lstack의 가장 위쪽에 위치한 문자가 rstack에 추가되어야 한다. 명령어에 D가 포함되는 경우는 커서가 오른쪽으로 한 칸 옮겨지는 것이므로 rstack의 가장 위쪽에 위치한 문자가 lstack에 추가 되게 구현한다. 명령어에 B가 포함되는 경우는 왼쪽에 있는 문자를 삭제시키는 것이므로 lstack의 가장 위쪽에 위치한 문자를 pop으로 제거시킨다. 명령어에 P가 포함되는 경우는 명령어에 있는 문자를 커서 왼쪽에 추가 시키면 되므로 lstack에 해당 문자를 push 해주면 된다. 그런 다음 정답을 출력하기 위해 lstack에 있는 모든 요소들을 pop해서 rstack에 push해준 후, rstack을 모두 pop해서 StringBuilder의 append로 추가해서 출력시켜주면 된다.

결과


백준 10845번 큐

문제

링크 : https://www.acmicpc.net/problem/10845

나의 풀이

import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        Queue<Integer> queue = new LinkedList<>();
        int n = Integer.parseInt(br.readLine());
        int b = -1;
        for(int i = 0; i < n; i++) {
            String str = br.readLine();
            if(str.contains("push")) {
                b = Integer.parseInt(str.split(" ")[1]);
                queue.offer(b);
            } else if(str.equals("pop")) {
                if(!queue.isEmpty()) {
                    System.out.println(queue.poll());
                } else {
                    System.out.println(-1);
                }
            } else if(str.equals("size")) {
                System.out.println(queue.size());
            } else if(str.equals("empty")) {
                if(queue.isEmpty()) {
                    System.out.println(1);
                } else {
                    System.out.println(0);
                }
            } else if(str.equals("front")) {
                if(!queue.isEmpty()) {
                    System.out.println(queue.peek());
                } else {
                    System.out.println(-1);
                }
            } else if(str.equals("back")) {
                if(!queue.isEmpty()) {
                    System.out.println(b);
                } else {
                    System.out.println(-1);
                }
            }
        }
    }
}

큐 라이브러리를 이용해서 구현하면 되는 문제다.

결과


백준 1158번 요세푸스 문제

문제

링크 : https://www.acmicpc.net/problem/1158

나의 풀이

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int k = sc.nextInt();
        
        Queue<Integer> queue = new LinkedList<>();
        for(int i = 1; i <= n; i++) {
            queue.offer(i);
        }
        
        StringBuilder sb = new StringBuilder();
        sb.append("<");
        while(!queue.isEmpty()) {
            for(int i = 0; i < k - 1; i++) {
                queue.offer(queue.poll());
            }
            sb.append(queue.poll());
            if(!queue.isEmpty()) {
                sb.append(", ");
            } 
        }
        sb.append(">");
        System.out.println(sb);
    }
}

큐가 비어있지 않을 때 까지 while문을 도는데 i가 0부터 k-1까지는 poll 메소드로 빼낸 값을 offer 메소드를 통해 큐의 맨뒤로 집어넣고 k번째가 되는 때에는 poll 메소드로 빼낸 값을 StringBuilder에 append로 추가시켜주고 이를 반복해준다. 그리고 마지막에 StringBuilder 값을 출력해주면 된다.

결과


백준 10866번 덱

문제

링크 : https://www.acmicpc.net/problem/10866

나의 풀이

import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
        
        ArrayDeque<Integer> deque = new ArrayDeque<>();
        for(int i = 0; i < n; i++) {
            String str = br.readLine();
            if(str.contains("push_front")) {
                deque.addFirst(Integer.parseInt(str.split(" ")[1]));
            } else if(str.contains("push_back")) {
                deque.addLast(Integer.parseInt(str.split(" ")[1]));
            } else if(str.equals("pop_front")) {
                if(!deque.isEmpty()) {
                    System.out.println(deque.pollFirst());
                } else {
                    System.out.println(-1);
                }
            } else if(str.equals("pop_back")) {
                if(!deque.isEmpty()) {
                    System.out.println(deque.pollLast());
                } else {
                    System.out.println(-1);
                }
            } else if(str.equals("size")) {
                System.out.println(deque.size());
            } else if(str.equals("empty")) {
                if(deque.isEmpty()) {
                    System.out.println(1);
                } else {
                    System.out.println(0);
                }
            } else if(str.equals("front")) {
                if(!deque.isEmpty()) {
                    System.out.println(deque.peekFirst());
                } else {
                    System.out.println(-1);
                }
            } else if(str.equals("back")) {
                if(!deque.isEmpty()) {
                    System.out.println(deque.peekLast());
                } else {
                    System.out.println(-1);
                }
            }
        }
    }
}

덱 라이브러리를 이용하여 구현하면 된다.

결과

profile
가보자고

0개의 댓글