본문 바로가기
카테고리 없음

프로그래머스 C# - 올바른 괄호

by 코딩하는 돼징 2023. 9. 7.
반응형

풀이

'(' ')'의 숫자들을 종이에 하나씩 적어보면 로직이 쉽게 보인다.

public class Solution {
    public bool solution(string s) {
        bool answer = true;
        Stack<char>stack = new Stack<char>();
        int right = 0;
        int left = 0;
        
        for(int i =0;i<s.Length;i++)
        {
            stack.Push(s[i]);
        }
        
        for(int i = 0; i<stack.Count;i++)
        {
            if(stack.Pop() == '(')
            {
                left++;
            }
            else
                right++;
            if(left >= right)
                answer = false;
        }
        
        return answer;
    }
}


계속 시간 초과가 떠서 어떻게 하지 하다가 스택을 사용 안하고 풀어보기로 했다.

public class Solution {
    public bool solution(string s) {
        bool answer = true;

        int right = 0;
        int left = 0;

        foreach(char c in s)
        {
            if(c=='(') left++;
            else
                right++;
            if(left < right)
            {
                answer = false;
                return answer;
            }
        }

        if(left != right)
        {
            answer = false;
            return answer;
        }

        return answer;
    }
}

 

통과됐다!

 

 

 

 

 

 

 

반응형

댓글