码迷,mamicode.com
首页 > 其他好文 > 详细

华为机试—括号匹配判断[去多余括号]

时间:2015-05-15 09:13:33      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:华为机试   括号匹配判断   去多余括号   

问题描述:
检查字符串表达式中的括号是否匹配;
左括号数目同有括号数目不相等即为不匹配;
去除多余的左括号或者右括号,优先保留先出现的括号;
匹配后去除无效的括号:如:((表达式)) 应为(表达式);

只考虑小括号,不考虑先出现右括号的情况;


要求实现函数: (字符串最长长度为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是输出的字符串!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void Bracket(char* src, char* dst)
{
	int nleft=0;
	int nright=0;
	int i=0;
	char c;
	if(src!=NULL)
	{
		while((c=src[i++])!='\0')
		{
			if(c=='(') nleft++;
			if(c==')') nright++;
		}
		int nmin=nleft>nright?nright:nleft;
		nleft=nmin;
		nright=nmin;
		i=0;
		int ldst=0;
		while ((c=src[i++])!='\0')
		{
			if (c=='(' && nleft-- >0)
			{
				dst[ldst++]=c;
			}
			if (c==')' && nright-- >0)
			{
				dst[ldst++]=c;
			}
			if(c!='(' && c!=')')
			{
				dst[ldst++]=c;
			}
		}
		dst[ldst]='\0';
		puts(dst);
	}
}

int main()
{
	char src[60];
	char dst[60];
	gets(src);
	Bracket(src,dst);
	return 0;
}

技术分享

华为机试—括号匹配判断[去多余括号]

标签:华为机试   括号匹配判断   去多余括号   

原文地址:http://blog.csdn.net/wtyvhreal/article/details/45726363

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!