본문으로 바로가기
728x90
반응형
SMALL

[프로그래머스] Lev 2. 괄호 회전하기

https://school.programmers.co.kr/learn/courses/30/lessons/76502

 

프로그래머스

SW개발자를 위한 평가, 교육의 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

 

 

28분경에 stack, queue 떠올림

괄호 판별 메서드 생각안남

실패

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


public class code {
    static Stack<String> stack = new Stack<>();
    static Set<String> dup = new HashSet<>();

    public static int solution(String s) {
        int answer = -1;
       answer = dfs(s, 0);

        return answer;
    }

    public static int dfs(String s, int cnt){
        if (dup.contains(s)){
            return cnt;
        }
        dup.add(s);

        String pre = s.substring(0, s.length()-1);
        String suf = s.substring(s.length()-1);

        String next = suf+pre;

        if (is괄호(s)){
            stack.clear();
            return dfs(next, cnt+1);
        } else {
            stack.clear();
             return dfs(next, cnt);
        }
    }


    public static boolean is괄호(String str){

        String[] arr = str.split("");
        for (int i = 0; i < arr.length; i++) {
            if (!(isPair(arr[i], "(",")") && isPair(arr[i], "[","]") && isPair(arr[i], "{","}"))){
                return false;
            }
        }
        return stack.empty();
    }

    public static boolean isPair(String a, String b, String c){
        if (a.equals(b)){
            stack.push(a);
        } else if(a.equals(c)){
            if (!stack.isEmpty() && stack.peek().equals(b)){
                stack.pop();
            }else {
                return false;
            }
        }
        return true;
    }


}
728x90
반응형
LIST