C language to achieve bracket matching-stack mode

When we are writing programs, we often encounter the problem of mismatched parentheses that lead to grammatical errors. Now we can implement the problem of parentheses matching by ourselves through the stack and understand its implementation details.
We assume that there are only two parentheses ()[] in the expression, and the nesting method is arbitrary. Checking whether the brackets match can be described by the concept of "expected urgency" (in fact, it means priority ).
Matching using the stack can perform this resolution process well:

	1,遍历字符串,如果遇到'(' 或者是'['则进行入栈操作,过滤掉其他字符
	2,如果遇到')'或是‘]’,则与栈顶元素进行判断,看是否匹配'('与‘)’匹配,
	‘[’与']'匹配。如果匹配成功,则出栈(注意这里并没有将‘)’或']'压入栈中。
	如果匹配失败,则可直接返回错误信息。
	3,当循环遍历结束时查看栈顶指针top是否为0(两两匹配的话就会最终结果就为0了),否则返回错误信息。

The following is the specific code implementation:

#define TRUE 1
#define FALSE 0
typedef int Status;
/**-- 字符匹配,str为需要判断是否匹配成功的字符串 --*/
Status  bracketMatch(char* str) {
	char stack[128];			//用数组模拟栈
	int top = 0;					//栈顶指针
	int i = 0;
	
	while(str[i] != '\0') {
		if (str[i] == '(' || str[i] == '[') {
			stack[top++] = str[i];
		} else if (str[i] == ')' || str[i] == ']' ) {
			if (stack[top - 1] == str[i] - 1) {		//这里根据ASCII码进行匹配的判断‘(’与‘)’的值差1
				top--;
			} else if (stack[top - 1] == str[i] - 2) {//这里根据ASCII码进行匹配的判断‘[’与‘]’的值差2
				top--;		//匹配成功出栈
			} else 
				return FALSE;		//失败即可立即返回
		}
		i++;
	}
	//最后判断top是否为0
	return top == 0 ? TRUE : FALSE;
	 
}

int main() {
	
	char str[128];
	scanf("%s",str);
	getchar();
	
	if (bracketMatch(str)) {
		printf("匹配成功!");
	} else {
		printf("匹配失败!");
	}
	return 0;
}

The following are the test results:

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_44184990/article/details/105038103