본문 바로가기
TIL

[코테연습] 1190. Reverse Substrings Between Each Pair of Parentheses

by 크라00 2024. 7. 11.

- 배열, 문자열문제

 

https://leetcode.com/problems/reverse-substrings-between-each-pair-of-parentheses/description/?envType=daily-question&envId=2024-07-11

 

- 문제분석

1. 괄호로 싸인 문자열이 있다. 

 s = "(ed(et(oc))el)"

 

2. 가장 안쪽 괄호부터 거꾸로 정렬할 경우 다음과 같이 나타난다. 

"leetcode"

 

3. 해당 방법을 코드로 구현해라.

 

- 문제풀이

1. 가장 안쪽 괄호를 구한다.

1-1. s.lastIndexOf() 함수와 s.indexOf() 함수를 사용한다.

1-2. 가장 안쪽 ')' 괄호를 구하기 위해서는 s.lastIndexOf("(") 부터 시작하여 탐색해야한다.

2. 해당 index 만큼 글자를 잘라 reverse 한다.

3. 양쪽 글자를 잘라놓은 뒤에 reverse 한것과 합친다.

4. while 문으로 해당 방법을 반복한다.

 

class Solution {
    public String reverseParentheses(String s) {

        while(true) {
            int lastIdx = s.lastIndexOf("(");
            String right = s.substring(lastIdx+1, s.length());
            int firstIdx = right.indexOf(")")+lastIdx+1;
            if (lastIdx < 0 || firstIdx < 0) {
                break;
            }
           
            String sub = s.substring(lastIdx+1, firstIdx);
            String nextStr = s.substring(0, lastIdx) + reverse(sub) + s.substring(firstIdx+1, s.length());
            s = nextStr;

        }

        return s;
    }
    
    String reverse(String s) {
        String[] arr = s.split("");
        StringBuilder sb = new StringBuilder();
        for(int i = arr.length-1; i >= 0; i--) {
            if(arr[i].equals("(") || arr[i].equals(")")) {
                continue;
            }
            sb.append(arr[i]);
        }
        return sb.toString();
    }
}