Algorithm

[c++]baekjoon 4949

denishong4.0 2021. 4. 3. 14:45
반응형

여기서 주의 할 점...

stack에 push된 게 없는 경우 top()이 호출되면 segmentation fault가 발생한다. 

그래서  if( !s.empty() )조건을 주고 s.top()함수를 호출하도록 추가했다. 여기서 많이 해맸는데, 좀더 좋은 방법이 있으신분은 댓글로 답변 부탁드립니다.

 

#include <iostream>
#include <stack>
#include <string.h>

using namespace std;

int main()
{
	int n=0,i = 0, count = 0;

	stack<char> s;
	char input[200];


	while( fgets(input, sizeof(input), stdin ) != NULL )
	{
		count = 0;
		if(input[0] == '.' ) break;

		for( i=0; i < strlen(input); i++)
		{
			if( input[i] == '(' || input[i] == '[' )
			{
				s.push( input[i] );
				//cout << "stack : " << s.top() << endl;
			}
			else if( input[i] == ')' || input[i] == ']' )
			{
				if( s.empty() ) 
				{
					count++;
					break;
				}
				else if( !s.empty() )
				{
					if( s.top() == '(' && input[i] == ')' )
					{
					//	cout << "stack is : " << s.top() << endl;
						s.pop();
					}
					else if( s.top() == '[' && input[i] == ']' )
					{
					//	cout << "stack is : " << s.top() << endl;
						s.pop();
					}
					else if( s.top() == '(' && input[i] == ']' )
					{
						count++;
						break;
					}
					else if( s.top() == '[' && input[i] == ')' )
					{
						count++;
						break;
					}
					else
					{
						count++;
						break;
					}
				}

			}
		}

		if( s.empty() && count == 0 )
			cout << "yes\n";
		else 
			cout << "no\n";

		if( !s.empty() )
		{
			//cout << "Stack is not empty!!" << endl;
			while( !s.empty() )
				s.pop();

			//cout << "Stack size is !!" << s.size() << endl;
		}
	}

	return 0;
}
반응형