Matching Parentheses?


General Statement: Read a string and determine whether each left parenthesis ‘(‘ has a matching right parenthesis ‘)’.

Input: The first line of the data set for this problem is an integer that represents the number of strings that follow. Each string is on a separate line.

Output: Output either MATCH or NO MATCH.
All letters are upper case.
The output is to be formatted exactly like that for the sample output given below.

Assumptions: All letters are upper case.
( and ) are the only enclosure symbols in the string.

Discussion: The left parenthesis must come before the right parenthesis in order to count as a matched set of parentheses.

Sample Input:
3
(3 + (7 * 2) – 6)
HELLO AND (WELCOME (TO THE) TCEA (CONTEST)
TODAY) IS ((SATURDAY())

Sample Output:
MATCH
NO MATCH
NO MATCH

Solutions :

#include <stdio.h>

int main ()
{
    int dataset;
    scanf ("%d", &dataset);
    getchar ();

    while ( dataset-- ) {
        char a [500];

        gets (a);

        int count = 0;

        for ( int i = 0; a [i] != 0; i++ ) {

            if ( a [i] == '(' )
                count++;
            else if ( a [i] == ')' )
                count--;

            if ( count < 0 )
                break;
        }

        if ( count == 0 )
            printf ("MATCH\n");
        else
            printf ("NO MATCH\n");
    }

    return 0;
}

One thought on “Matching Parentheses?

  1. I got the number of this one all right. here goes:

    #include
    #include
    int main(){
    char string[99];
    int i,j,k,l,x,count,counter;
    printf(“please enter the number of inputs: “);
    scanf(“%d”,&x);
    fgets(string,99,stdin);
    for(j=0;j<99;j++){
    if(string[j]=='\n'){
    string[j]='\0';
    }
    }
    for(i=1;i<=x;i++){
    fgets(string,99,stdin);
    for(j=0;j<99;j++){
    if(string[j]=='\n'){
    string[j]='\0';
    }
    }
    l=strlen(string)-1;
    count=0;
    for(k=0;k<=l;k++){
    if(string[k]=='('){
    count=count+1;
    }
    }
    counter=0;
    for(k=0;k<=l;k++){
    if(string[k]==')'){
    counter=counter+1;
    }
    }
    if(count==counter&&count!=0){
    printf("MATCH\n");}
    else if(count!=counter){
    printf("NO MATCH\n");
    }
    else{printf("please enter a string with parentheses.\n");}
    }
    return 0;
    }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s