ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • section5.2
    알고리즘 2025. 8. 14. 10:28
    입력된 문자열에서 소괄호 ( ) 사이에 존재하는 모든 문자를 제거하고 남은 문자만 출력하는 프로그램을 작성하세요.
    
    입력설명
    첫 줄에 문자열이 주어진다. 문자열의 길이는 100을 넘지 않는다.
    
    출력설명
    남은 문자만 출력한다.
    
     입력예제 1
    (A(BC)D)EF(G(H)(IJ)K)LM(N)
    
    출력예제 1
    EFLM

     

     

     

    ANSWER

    public class Question2 {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            String s = sc.next();
            System.out.println(solution(s));
        }
    
        public static String solution(String s) {
            String answer = "";
            Stack<Character> stack = new Stack<>();
    
            // (A(BC)D)EF(G(H)(IJ)K)LM(N)
            for (char x : s.toCharArray()) {
                if (x != ')') {
                    stack.push(x);
                } else {
                    while (!stack.pop().equals('(')) {
                        stack.peek();
                    }
                }
            }
    
            for (char x : stack) {
                answer += x;
            }
    
            return answer;
        }
    }

     

     

     

    SOLUTION

    public class Answer2 {
        public static void main(String[] args) {
            Answer2 T = new Answer2();
            Scanner sc = new Scanner(System.in);
            String str = sc.next();
            System.out.println(T.solution(str));
        }
    
        public String solution(String str) {
            String answer = "";
            Stack<Character> stack = new Stack<>();
    
            for (char x : str.toCharArray()) {
                if (x == ')') {
                    while (stack.pop() != '(');
                } else {
                    stack.push(x);
                }
            }
    
            for (int i = 0; i < stack.size(); i++) {
                answer += stack.get(i);
            }
    
            return answer;
        }
    }
    • 몰랐던 점은 stack.pop() 으로 while문 돌려도 어쨌든 값이 빠져나온다는 것, 그래서 자꾸 stack이 비었다는 오류가 떴었다
    728x90

    '알고리즘' 카테고리의 다른 글

    section5.4  (1) 2025.08.14
    section5.3  (2) 2025.08.14
    section5.1  (3) 2025.08.14
    section3.5  (1) 2025.08.13
    section3.4  (1) 2025.08.13
Designed by Tistory.