数据结构:(堆栈应用)括号匹配性(2019.2.27)

 

1.对于一个字符串的循环条件

//for(i = 0; i < strlen(str); i++){   //自己写的 
    for(i = 0; str[i]; i++){                 //朱老师写的 

         ...
   }

 

2.对于代码优化

 

    /*    
    if(num > 0){     //自己
        return FALSE;
    }else{
        return TRUE;
    }
    */
    return num == 0;     //朱老师

/*括号匹配性 

假设从键盘输入的字符串仅仅只由“(”和“)”组成,要求编程判断匹配性。
	处理手法:
		设置一个变量num,且初值为0;
		1、遇到(,num++;
		2、遇到),num--;
		3、若num < 0,发现失配,立刻结束;                                      //右括号多 
		4、字符串内容全部处理完毕后,若num > 0,为失配;== 0,表明括号匹配。    //左括号多 
		
*/

#include<stdio.h>
#include<string.h>

typedef unsigned char  boolean;
#define  TRUE    1
#define  FALSE   0

boolean isMarketMatch(char *str, int *misMatchIndex);
void showWrongMatch(char *str, int misMatchIndex);

void showWrongMatch(char *str, int misMatchIndex){
	int i;
	
	printf("原字符串为:%s\n", str);
	printf("错误位置在:");
	
	for(i = 0; i < misMatchIndex; i++){
		printf(" ");
	}
	printf("^\n");
}

boolean isMarketMatch(char *str, int *misMatchIndex){
	int num = 0;
	int i;
	
	//for(i = 0; i < strlen(str); i++){   //自己写的 
	//for(i = 0; str; i++){                 
	for(i = 0; str[i]; i++){          //朱老师写的
		if(str[i] == '('){
			num++;
		}else if(str[i] == ')'){
			num--;
		}
		
		if(num < 0){
			*misMatchIndex = i;
			return FALSE;
		}
		//printf("*\n");
	}
	
	//printf("\nnum=%d\n\n", num);
	if(num > 0){
		*misMatchIndex = i;
		//*misMatchIndex = i-1;
		return FALSE;
	}else{
		return TRUE;
	}
	
	
} 

void main(void){
	char str[80];
	int misMatchIndex;
	
	printf("请输入一串字符(只包含(和)):");
	gets(str);
	
	if(isMarketMatch(str, &misMatchIndex)){
		printf("括号匹配!\n");
	}else{
		printf("括号不匹配!\n");
		showWrongMatch(str, misMatchIndex);
	}
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

安安csdn

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值