관리 메뉴

Mini

백준 4949 cpp // 괄호검사 알고리즘 본문

Algorithm/스택

백준 4949 cpp // 괄호검사 알고리즘

Mini_96 2023. 8. 22. 17:54

https://www.acmicpc.net/problem/4949

 

4949번: 균형잡힌 세상

각 문자열은 마지막 글자를 제외하고 영문 알파벳, 공백, 소괄호("( )"), 대괄호("[ ]")로 이루어져 있으며, 온점(".")으로 끝나고, 길이는 100글자보다 작거나 같다. 입력의 종료조건으로 맨 마지막에

www.acmicpc.net

*괄호검사 알고리즘

왼괄호 ->push

오른괄호->빈스택인경우 -> wrong    //   

                -> 올바른짝이있는경우 ->pop

                ->안맞는짝인경우 ->wrong

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

작업후  (왼괄호가 )남아있는경우 ->wrong

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

유효하면 yes

아니면 no출력

 

* 내코드

#include<bits/stdc++.h>
using namespace std;

string str;

int main() {
	ios_base::sync_with_stdio(0);
	cin.tie(0); cout.tie(0);

	while (true) {
		stack<char> s;
		getline(cin, str);
		if (str == ".") break;

		bool is_wrong = false;
		for (char c : str) {
			//1.( -> push
			//2.) and 현재==( ->pop
			//3.) and 현제 == 빈칸 ->no

			if (c == '(') {
				s.push(c);
			}
			else if (c == '[') {
				s.push(c);
			}
			else if (c == ')') {
				if (s.size() && s.top() == '(') {
					s.pop();
				}
				else if (s.size() && s.top() != '(') {
					is_wrong = true;
					break;
				}
				else if (s.empty()) {
					is_wrong = true;
					break;
				}
			}
			else if (c == ']') {
				if (s.size() && s.top() == '[') {
					s.pop();
				}
				else if (s.size() && s.top() != '[') {
					is_wrong = true;
					break;
				}
				else if (s.empty()) {
					is_wrong = true;
					break;
				}
			}
		}

		//짝이 안맞는경우
		//ex) [)
		if (is_wrong) {
			cout << "no\n";
			continue;
		}

		//폭팔안된 (가 남아있으면 no
		if (s.size()) {
			cout << "no\n";
		}
		else {
			cout << "yes\n";
		}
	}
}

 

*바킹독 코드

or 연산자를 이용 =>  depth를 줄여보자.

// Authored by : BaaaaaaaaaaarkingDog
// Co-authored by : -
// http://boj.kr/9dd230a7a6cf4fdaa3f2abde6c96c59c
#include <bits/stdc++.h>
using namespace std;

int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  while(true){
    string a;
    getline(cin, a);
    if(a == ".") break;
    stack<char> s;
    bool isValid = true;
    for(auto c : a){
      if(c == '(' || c == '[') s.push(c);
      else if(c == ')'){
        if(s.empty() || s.top() != '('){
          isValid = false;
          break;
        }
        s.pop();
      }
      else if(c == ']'){
        if(s.empty() || s.top() != '['){
          isValid = false;
          break;
        }
        s.pop();
      }
    }
    if(!s.empty()) isValid = false;
    if(isValid) cout << "yes\n";
    else cout << "no\n";
  }
}