Nanyang Science and Technology OJ topic exercises---bracket pairing problem __ algorithm (data structure)

Source: Internet
Author: User

Here's my algorithm:

#include <iostream>
using namespace std;

int IsMatch (char* str)
{
	char stack[10000];
	int i=0;
	memset (stack,0,sizeof (stack));
	char *p=str;
	if (*p== '] ' | | *p== ') return
		0;
	while (*p!= ' ")
	{
		if (*p== '] ' | | | | *p== ') '
		) {
			switch (*p)
			{case
			'] ':
				if (* (p-1) = = ' [')
				{
					i--;
					stack[i]= ' n ';
				}
				else return 0;
				break;
			Case ') ':
				if (* (p-1) = = ' (')
				{
					i--;
					stack[i]= ' n ';
				}
				else return 0;
			}
		}
		else
		{
			stack[i++]=*p;
		}
		p++;
	}
	if (i==0 && stack[i]== ') return
		1;
	else return 
		0;

}

int main ()
{
	int N;
	Char str[10000];
	cin>>n;
	while (n--)
	{
       cin>>str;
	   if (IsMatch (str)) cout<< "Yes" <<endl;
	   else
	   cout<< "No" <<endl;
	}
	return 0;
}

Algorithm Reviews:

Personal feeling is to see your understanding of the stack, no difficulty


Attached OJ system based on memory footprint and time recommended by the optimal solution: (since I have not yet studied the STL, or back to study this algorithm)

#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main ()
{
int n;
cin>>n;
while (n--)
{  
vector<char> vec;
string ch;
Vec.push_back (");
cin>>ch;
for (int i=0;i<ch.length (); i++)
{
vec.push_back (ch[i]);
if (Vec.back ()-1 = * (Vec.end ()-2) | | | Vec.back ()-2 = = (Vec.end ()-2))
{
vec.pop_back ();
Vec.pop_back ();
}
if (Vec.size () ==1)
cout<< "Yes" <<endl;
else
cout<< "No" <<endl;
}
return 0;
}



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.