2021.02.10 연습

 

  • 사용언어 : java

 


class Solution {
    public int maxDepth(String s) {
        
        if (s == "" || s.length() == 1 ) {
            return 0;
        }
        
        int maxDepth = 0;
        int count = 0;
        
        for (char i : s.toCharArray()) {
            
            if (i == '(') {
                count++;
            } else if (i == ')') {
                count--;
            } 
            maxDepth = Math.max(maxDepth, count);
            
        }
        
        return maxDepth; 
        
    }
}

Runtime: 0 ms, faster than 100.00% of Java online submissions for Maximum Nesting Depth of the Parentheses. Memory Usage: 37.1 MB, less than 60.40% of Java online submissions for Maximum Nesting Depth of the Parentheses.



class Solution {
    public int balancedStringSplit(String s) {
        
        int count = 0;
        int curr = 0;
        
        char c = ' ';
        
        for (char i : s.toCharArray()) {
            
            if (curr == 0) {
                c = i;
                curr++;
            } else {
                if (i == c) {
                    curr++;   
                } else {
                    curr--;
                }
                if (curr == 0) {
                    count++;
                }
            }

        }
        
        return count;
        
    }
}

Runtime: 0 ms, faster than 100.00% of Java online submissions for Split a String in Balanced Strings. Memory Usage: 37.4 MB, less than 24.47% of Java online submissions for Split a String in Balanced Strings.

  • 다른 코드 참고
//stack 사용

 public int balancedStringSplit(String s) {
        Stack<Character> stack = new Stack();
        int res = 0;
        //going over string chars
        for (char ch : s.toCharArray()) {
            //check if char doesn't balance the previous one, or the stack is empty
            if (stack.isEmpty() || stack.peek() == ch)
                stack.push(ch);
            //if chars are balanced - remove the pair
            else
                stack.pop();
            //if stack is empty - all pairs are balanced and we have a balanced substring
            if (stack.isEmpty()) 
                res++;
        }
        return res;
    }