博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

括号匹配问题

Posted on 2011-08-15 22:39  ChessYoung  阅读(268)  评论(0编辑  收藏  举报

某个字符串中有左右括号,和常见的数学式子一样,任何一个左括号都是从内向外的与它在右边、距离最近的右括号相匹配。编写一个程序找出无法匹配的左括号与右括号,并在下方标出来。

自己模仿:

#include "stdafx.h"
#include <iostream>
using namespace std;

const int SIZE = 100;
void ParCount(char line[], char error[], int &flags);

int _tmain(int argc, _TCHAR* argv[])
{
	char line[] = "((A+B)+(A+B)))";
	char error[SIZE] = {'\0'};
	
	//为0表示没有错误
	int flags = 0;

	ParCount(line, error, flags);

	if (0 == flags)
	{
		cout << "Correct!\n";
	} 
	else
	{
		printf("%s", line);
		printf("\n%s", error);
	}

	return 0;
}

void ParCount( char line[], char error[], int &flags )
{
	int left = 0;
	int right = 0;
	int loc = -1;

	int location[SIZE] = {0};
	int i = 0;

	for (i = 0; line[i] != '\0'; ++i)
	{
		error[i] = ' ';
		
		if (line[i] == '(')
		{
			location[++loc] = i;
			++left;
		} 
		else		
		if (line[i] == ')')
		{
			if (left <= right)
			{
				error[i] = '@';
				flags = 1;
			}
			else
			{
				++right;
				--loc;
			}
		} 		
	}
	
	error[i] = '\0';
	if (loc >= 0)
	{
		flags = 1;
		for (i = 0; i<=loc;++i)
		{
			error[location[i]] = '#';
		}
	}

}

原版: 

/* ------------------------------------------------------ */
/* FUNCTION par_count :                                   */
/*    Given an input string containing ( and ), this      */
/* function counts the # of ('s and )'s and indicates the */
/* positions of those incorrect placed ('s and )'s.  The  */
/* input string is stored in line[].  error[], which      */
/* stores a set of error position indicators, is returned */
/* and thus can be printed below the input line so that   */
/* all error positions are macthed with the input.  'sw'  */
/* is an indicator variable, =0 means no error.           */
/*                                                        */
/* Copyright Ching-Kuang Shene               July/08/1989 */
/* ------------------------------------------------------ */

#define  MAXLENGTH  100
#define  YES          1
#define  NO           0

void par_count(char line[], char error[], int *sw)
{
     int  location[MAXLENGTH];
     int  left    =  0;
     int  right   =  0;
     int  loc_ptr = -1;
     int  i;

     *sw = NO;                /* assume there is no error */
     for (i = 0; line[i] != '\0'; i++)
     {
         /* scan the input*/
          error[i] = ' ';     /* initial to no error mark */

          if (line[i] == '(')
          { /* is it a '(' ?          */
               location[++loc_ptr] = i; /* YES, save pos  */
               left++;        /* and increase '(' count   */
          }
          else
          if (line[i] == ')') /* or if it is a ')'   */
               if (left <= right)
               {/* too many )'s ?      */
                    error[i] = '?';/* YES, record a mark  */
                    *sw      = YES;/* and set error switch*/
               }
               else
               {
                    right++;  /* no error, inc. # of )'s  */
                    loc_ptr--;/* remove the matched (     */
               }
     }
     error[i] = '\0';         /* append a '\0'            */
     if (loc_ptr >= 0)
     {      /* are there more ('s ?     */
          *sw = YES;          /* YES, all of them are err.*/
          for (i = 0; i <= loc_ptr; i++) /* therefore set */
               error[location[i]] = '$'; /* error marks.  */
     }
}


/* ------------------------------------------------------ */

#include <stdio.h>

int main(void)
{
     char  line[MAXLENGTH];
     char  error[MAXLENGTH];
     int   error_sw;

     printf("\nParenthesis Counting Program");
     printf("\n============================\n");
     printf("\nInput a line please\n");
     gets(line);
     par_count(line, error, &error_sw);
     if (error_sw == NO)
          printf("\nCorrect Input.");
     else
          printf("%s", error);

     return 0;
}