[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] LV.2 ์˜ฌ๋ฐ”๋ฅธ ๊ด„ํ˜ธ (์ž๋ฐ” java)

 

1. ๋ฌธ์ œ : https://school.programmers.co.kr/learn/courses/30/lessons/12909

 

2. ํ’€์ด

1) count๋ฅผ ํ™œ์šฉํ•œ ํ’€์ด

2) stack์„ ํ™œ์šฉํ•œ ํ’€์ด

 

3. ์ฝ”๋“œ

1)

class Solution {
    boolean solution (String s) {
        boolean answer = false;
        int count = 0;
        for (int i = 0; i < s.length(); i++) {
            if(s.charAt (i) =='(') count++;
            else count--;
            if (count < 0) break;
        }
        if(count == 0) answer = true;
        return answer;
    }
}

2)

import java.util.*;

class Solution {
    boolean solution(String s) {
        boolean answer = true;
        Stack<Character> stack = new Stack<>();
        
        for(int i = 0; i < s.length(); i++){
            char c = s.charAt(i);
            
            //์—ฌ๋Š” ๊ด„ํ˜ธ์ผ ๋•Œ
            if(c == '('){
                stack.push(c);
            }
            
            //๋‹ซ๋Š” ๊ด„ํ˜ธ์ผ ๋•Œ
            if(c == ')'){
                if(stack.size() == 0){
                    return false;
                }
                else stack.pop();
            }
        }
        if(stack.size() != 0) answer = false;

        return answer;
    }
}
  • ๋„ค์ด๋ฒ„ ๋ธ”๋Ÿฌ๊ทธ ๊ณต์œ ํ•˜๊ธฐ
  • ๋„ค์ด๋ฒ„ ๋ฐด๋“œ์— ๊ณต์œ ํ•˜๊ธฐ
  • ํŽ˜์ด์Šค๋ถ ๊ณต์œ ํ•˜๊ธฐ
  • ์นด์นด์˜ค์Šคํ† ๋ฆฌ ๊ณต์œ ํ•˜๊ธฐ