본문 바로가기

Java/Java 알고리즘 LeetCode

[LeetCode- Part. 1] 1. 가장 바깥 괄호제거 (+ StringBuilder, substring)

반응형

https://leetcode.com/problems/remove-outermost-parentheses/

 

Remove Outermost Parentheses - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

 

class Solution {
    public String removeOuterParentheses(String s) {
        //10
        int cnt=0;
        String str="";
        String answer="";
        for(char c: s.toCharArray()){
            if(c=='(') cnt++;
            else cnt--;
            
            str+=c;
            System.out.println(str);
            if(cnt==0){
                answer+=str.substring(1, str.length()-1);  
                str="";
            } 
        }
        return answer;
    }
}

class Solution {
    public String removeOuterParentheses(String s) {
        //괄호의 분해후 가장 바깥쪽 괄호 제거
        //여는 괄호와 닫는 괄호 개수를 센다.
        //open, close

        //모두 유효한 괄호이므로 예외처리 안해도 된다.
        //if(s.charAt(0)==')') return answer;
        int cnt=0;
        
        StringBuilder sb = new StringBuilder();
        for(char c:s.toCharArray()){
            if(c=='(' ){
                if(cnt!=0) sb.append(c);
                cnt++;  
            } 
            else if(c==')'){
                cnt--;
                if(cnt!=0) sb.append(c);
            } 
        }
        
        return sb.toString();
    }
}
반응형