문제

  • 링크
    title: "코딩테스트 연습 - 괄호 회전하기"
    image: "https://image.freepik.com/free-vector/landing-page-template-for-a-website_23-2147782747.jpg"
    description: "다음 규칙을 지키는 문자열을 올바른 괄호 문자열이라고 정의합니다."
    url: "https://school.programmers.co.kr/learn/courses/30/lessons/76502?language=java"
    

    문제 풀이

    문제 접근

    이 코드는 문자열 s의 모든 회전된 문자열에 대해, 해당 문자열이 올바른 괄호 문자열인지 확인하는 방식으로 문제를 해결합니다.

  1. 주어진 문자열을 한 글자씩 회전시켜 총 n개의 문자열을 생성합니다.
  2. 각 회전된 문자열이 올바른 괄호 문자열인지 확인합니다.
    • 올바른 괄호 문자열인지 확인하는 함수(isCorrected)는 스택을 사용하여 여는 괄호와 닫는 괄호가 올바르게 매칭되는지 판단합니다.
  3. 올바른 괄호 문자열의 개수를 계산하여 반환합니다.

    간단한 수도 코드 정리

    ```pseudocode function solution(s): answer = 0 sb = StringBuilder(s)

    for i from 0 to length(s) - 1: if isCorrected(sb.toString()): answer += 1

     // 문자열 회전
     append first character of sb to the end
     delete first character of sb
    

    return answer

function isCorrected(s): stack = empty stack

for each character in s:
    if stack is empty:
        push character to stack
    else if top of stack matches character:
        pop stack
    else:
        push character to stack

return true if stack is empty, otherwise false

function isMatched(a, b): return true if (a, b) is one of (“[”, “]”), (“{“, “}”), (“(“, “)”)


---
## 풀이 코드
```java
import java.util.*;

class Solution {
    public int solution(String s) {
        int answer = 0;
        StringBuilder sb = new StringBuilder(s);
        
        for (int i = 0; i < s.length(); i++) { // n-1번 검사
            if (isCorrected(sb.toString())) {
                answer++;
            }
            
            // 회전
            sb.append(sb.substring(0, 1));
            sb.delete(0, 1);
        }
        
        return answer;
    }
    
    public static boolean isCorrected(String s) {
        boolean check = false;
        Stack<String> stack = new Stack<>();
        
        for (String t : s.split("")) {
            if (stack.isEmpty()) {
                stack.push(t);
            } else if (isMatched(stack.peek(), t)) {
                stack.pop();
            } else {
                stack.push(t);
            }
        }
        
        if (stack.isEmpty()) {
            check = true;
        } else {
            check = false;
        }
        
        return check;
    }
    
    public static boolean isMatched(String a, String b) {
        boolean check = false;
        
        if (a.equals("[") && b.equals("]")) {
            check = true;
        } else if (a.equals("(") && b.equals(")")) {
            check = true;
        } else if (a.equals("{") && b.equals("}")) {
            check = true;
        } else {
            check = false;
        }
        
        return check;
    }
}