코린이의 소소한 공부노트

[LeetCode/Easy] 1021. Remove Outermost Parentheses 본문

코딩테스트 풀이/JAVA

[LeetCode/Easy] 1021. Remove Outermost Parentheses

무지맘 2023. 6. 7. 20:02

1. Input

1) String s

 

2. Output

1) s에서 가장 바깥 소괄호를 없앤 나머지를 반환

- s는 유효한 괄호들로 이루어져 있다.

 

3. Constraint

1) 1 <= s.length <= 10^5

2) s'('')'로 이루어져 있다.

 

4. Example

Input: s = "(()())(())" -> Output: "()()()"

Input: s = "(()())(())(()(()))" -> Output: "()()()()(())"

Input: s = "()()" -> Output: ""

설명:

- “(()())”“(())”로 이루어져 있다. -> 가장 바깥 소괄호를 없애면 “()()”“()”이 된다.

- “(()())”“(())”“(()(()))”로 이루어져 있다. -> 가장 바깥 소괄호를 없애면 “()()”“()”“()(())”이 된다.

- “()”“()”로 이루어져 있다. -> 가장 바깥 소괄호를 없애면 둘다 “”이 된다.

 

5. Code

1) 첫 코드(2023/06/07)

class Solution {
    public String removeOuterParentheses(String s) {
        int count = 1, start = 0;
        StringBuilder sb = new StringBuilder();
        for(int i=1 ; i<s.length() ; i++){
            char c = s.charAt(i);
            if(c=='(') count++;
            else count--;
            if(count==0){
                sb.append(s.substring(start+1, i));
                start = i+1;
                count = 0;
            }
        }
        return sb.toString();
    }
}

- 74%, 93%