Parentheses matching problem (Nanyang 2) and parentheses matching Nanyang 2

Source: Internet
Author: User

Parentheses matching problem (Nanyang 2) and parentheses matching Nanyang 2
// Check the matching of parentheses. It is not too complicated to construct the stack using the stack idea. In this question, it is actually an array.
/* For example, consider the following sequence of parentheses:
[([] [])] Ask If brackets match
*/
# Include <cstdio>
# Include <cstring>
Int main ()
{
Int top, I;
Char a [1, 1010], B [2, 1010];
While (scanf ("% s", )! = EOF)
{
Top = 1; // top points to the next position under the B Array
B [top ++] = a [0];
For (I = 1; I <strlen (a); I ++)
{
If (a [I] = '(' | a [I] = '[') // in this case
B [top ++] = a [I];
Else if (a [I] = ')' & B [top-1] = '(') // overwrites the array B.
Top --;
Else if (a [I] = ']' & B [top-1] = '[')
Top --;
Else
{// Stack the remaining two cases
B [top ++] = a [I];
}
}
If (top = 1)
Printf ("matching brackets! \ N ");
Else
Printf ("Parentheses do not match !!! \ N ");
}
Return 0;
}
 
[ACM problem] Nanyang Institute of Technology Online evaluation question 15 matching brackets (2)

I roughly tested it.
This) [) (] (in this example, your answer is 6, but there are at least four, which means you have not considered completely

Another problem is that you need to save the result to an array and output the result at one time.

Brackets matching

# Include <stdio. h>
# Deprecision MAX 100
Int match (char * str)
{
Char stack [MAX], * p = stack;
While (* str)
{
Switch (* str)
{
Case '(':
{
* P ++ = * str;
Break;
}
Case ')':
{
If (* -- p! = '(')
Return 0;
Break;
}
Case '[':
{
* P ++ = * str;
Break;
}
Case ']':
{
If (* -- p! = '[')
Return 0;
Break;
}
Case '{':
{
* P ++ = * str;
Break;
}
Case '}':
{
If (* -- p! = '{')
Return 0;
Break;
}
}
Str ++;
}
If (stack = p)
Return 1;
Else
Return 0;
}

Int main ()
{
Char str [MAX];
Gets (str );
If (match (str ))
{
Printf ("match \ n ");
}
Else
{
Printf ("not match \ n ");
}
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.