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;
}