728x90
SMALL

using System;

public class Solution {
    public bool solution(string s) {
        int count = 0;
        
        for(int i = 0;i<s.Length;i++)
        {
            count = s[i] == '(' ? count+1 : count-1;

// if/else문으로 하면 시간초과라고 안된다. 배열에서 (면 카운트를 플러스, 아니면 카운트를 마이너스
            if(count < 0)
            {
                return false;

// 맨 처음에 count가 -1이하가 되면 바로 false를 반환하게 한다. )가 앞에 나오면 거기서 게임이 끝난 것이기 때문에 시간을 절약할 수 있기도 하다.

// 앞에서 count가 -1이 되면 (가 있어도 해결이 안되니까, 예를 들어 )(면 에러 그렇게 되게 코드가 되어 있다.
            }
        }

        return count == 0;
    }
}

 

 

/////

자바

 

 

import java.util.Stack;
class Solution {
    boolean solution(String s) {
        boolean answer = true;  
        String res = "YES";
        Stack<Integer> st = new Stack<>();

        for (int i = 0; i < s.length(); i++) 
        {
                if (s.charAt(i) == '(') 
                {
                    st.push(1);
                } 
                else if (s.charAt(i) == ')') 
                {
                    if (st.isEmpty()) 
                    {
                        answer = false;
                        break;
                    } 
                    else 
                    {
                        st.pop();
                    }
                }
            }

            if(!st.isEmpty()) 
            {
                answer = false;
            }

            System.out.println(res);
        return answer;
    }   
}

 

 

 

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++;
            }
            if(s.charAt(i) == ')')
            {
                count--;
            }
            
            if(count < 0)
            {
                break;
            }
        }
        
        if(count == 0)
        {
            answer = true;
        }

        return answer;
    }
}
728x90

설정

트랙백

댓글