본문 바로가기
Algorithm/leetcode

[leetcode] 1614. Maximum Nesting Depth of the Parentheses

by 세류오 2023. 8. 29.

LeetCode - The World's Leading Online Programming Learning Platform

 

Maximum Nesting Depth of the Parentheses - LeetCode

Can you solve this real interview question? Maximum Nesting Depth of the Parentheses - A string is a valid parentheses string (denoted VPS) if it meets one of the following: * It is an empty string "", or a single character not equal to "(" or ")", * It ca

leetcode.com

문제 이해

가장많은 중첩 괄호의 수를 구하여 반환

문제 풀이

‘(’일 때 push, ‘)’일 떄 pop
stack의 size = 중첩된 ‘(’의 개수
Math.max(a, b)를 이용해 가장 많은 중첩 수를 변수에 저장 후 값을 return

class Solution {
    public int maxDepth(String s) {
        //Stack에 가장 많은 '('가 존재할 때
        Stack<Character> st = new Stack<>();
        int depth = 0;

        for(int i = 0; i < s.length(); i++){

            char c = s.charAt(i);
            if(c == '(') {
                st.push(c);
                depth = Math.max(depth, st.size());
            } 
            if(c == ')') {
                st.pop();
            }
        }
        return depth;
    }
}