括号匹配判断
问题描述:
检查字符串表达式中的括号是否匹配;
左括号数目同有括号数目不相等即为不匹配;
去除多余的左括号或者右括号,优先保留先出现的括号;
匹配后去除无效的括号:如:((表达式)) 应为(表达式);
只考虑小括号,不考虑先出现右括号的情况;
要求实现函数: (字符串最长长度为60;表达式正确性不需要考虑)
void Bracket(char* src, char* dst);
如果匹配则通过dst输出原串;
如果不匹配则根据要求去处多于括号后通过dst输出匹配后的串;
示例
输入:12+(345*25-34) 输出:12+(345*25-34)
输入:12+(345*(25-34) 输出: 12+(345*25-34)
输入:(12+345)*25)-34 输出: (12+345)*25-34
输入:(543+(256-43)*203))+24
输出:(543+(256-43)*203)+24
输入:((1+2)*((34-2))+((2*8-1)
输出:((1+2)*(34-2)+2*8-1)
void Bracket(char* src, char* dst);只能在这个函数中实现,不允许用栈。不允许另写函数并加以调用。src是输入的字符串,dst是输出的字符串!
以下是我的代码,请大家多多指点!
//Assumption:
/*
1. there are only number(0,...9) and math operation(+,-,*,/), no other alphabet and '$'
2. redundant expression is just like ((expression)), no (((expression)))
3. the expression is correct, including length less than 60 and the first bracket is '('
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LENGTH 60
void Bracket(char* src, char* dst)
{
char BracketNum[60];
int LeftBktNum=0, RightBktNum=0;
char* tmpIn = src;
char* pHead = BracketNum;
char* pTail = BracketNum+59;
int i,j,jj;
bool bRedundant = 0;
//1.count the number of bracket
while(*tmpIn)
{
if( *tmpIn == '(' )
{
LeftBktNum ++;
*pHead++ = tmpIn - src;
}
else if( *tmpIn == ')' )
{
RightBktNum ++;
*pTail-- = tmpIn - src;
}
tmpIn ++;
}
//2.delete unmatch bracket
if( LeftBktNum > RightBktNum )
{
do
{
pHead --;
src[*pHead] = '$'; //the flag indicate to be deleted bracket
LeftBktNum --;
}while(LeftBktNum > RightBktNum);
}
else if( LeftBktNum < RightBktNum )
{
do
{
pTail ++;
src[*pTail] = '$'; //the flag indicate to be deleted bracket
RightBktNum --;
}while(LeftBktNum < RightBktNum);
}
//3.delete redundant bracket
for( i=1,j=0; i<LeftBktNum; i++)
{
if( BracketNum[i] - BracketNum[i-1] == 1 )
{
//record left bracket
bRedundant = 1;
BracketNum[LeftBktNum+j] = BracketNum[i];
if( i == LeftBktNum-1 ) BracketNum[LeftBktNum+j+1] = 60;
else BracketNum[LeftBktNum+j+1] = BracketNum[i+1];
j+=2;
}
}
if(bRedundant)
{
for( i=59; i>( 60 - RightBktNum ); i--)
{
if( BracketNum[i-1] - BracketNum[i] == 1 )
{
//record right bracket
jj = 0;
while(jj<j)
{
if( BracketNum[LeftBktNum+jj] < BracketNum[i] && BracketNum[i] < BracketNum[LeftBktNum+jj+1] )
{
src[ *(BracketNum+LeftBktNum+jj) ] = '$';
src[ *(BracketNum+i) ] = '$';
if( BracketNum[LeftBktNum+jj-1] == BracketNum[LeftBktNum+jj]) BracketNum[LeftBktNum+jj-1] = BracketNum[LeftBktNum+jj+1];
}
jj += 2;
}
}
}
}
//4.write src into dst
while (*src)
{
if ('$'!=*src)
{
*dst++=*src;
}
src++;
}
*dst='/0';
}
void main()
{
char strin[MAX_LENGTH] = "((1+2)*((34+(3-2))+(((9*4)))+((2*8-1)";///"((1+2)*((34+(3-2))+9*4)+((2*8-1)";
char strout[MAX_LENGTH];
memset(strout,0,sizeof(strout));
printf("the input is %s/n",strin);
Bracket(strin,strout);
printf("the output is %s/n",strout);
getchar();
}