括号匹配

/*
    Author:Cuinp
	Date:2014/9/1
*/
#include <stdio.h>
#include <string.h>
#define BUFSIZE 64
bool bracesMatch(char *);
int main() {
	char buf[BUFSIZE];
	memset(buf,0,BUFSIZE);
	while(1) {
		printf("Please input braces express(quit):\n");
		fgets(buf,BUFSIZE,stdin);
		if(strcmp(buf,"quit") == 0){
			break;
		}
		if(bracesMatch(buf) == true){
			printf("Braces macth successfully!\n");
		} else {
			printf("Braces macth failed!\n");
		}
	}
	return 0;
}
bool bracesMatch(char *exp) {
	char stack[BUFSIZE];
	int sp = -1;			// Stack pointer
	char ch = '\0';
	int i = 0;
	while(exp[i] != '\0') {
		ch = exp[i];
		switch(ch) {
			case '{':
			case '[':
			case '(':
				stack[++sp] = exp[i];	// 'Left braces' inStack
				break;
			case '}':
				if(sp!= -1 && stack[sp] == '{') {
					sp--;				// If match stack top item the outStack
				} else {
					return false;
				}
				break;
			case ']':
				if(sp!= -1 && stack[sp] == '[') {
					sp--;
				} else {
					return false;
				}
				break;
			case ')':
				if(sp!= -1 && stack[sp] == '(') {
					sp--;
				} else {
					return false;
				}
				break;
			default:
				break;			// Read other character the skip
		} // Switch end
		i++;
	} // While end

	if(sp == -1) {				// If stack is empty
		return true;
	} else {
		return false;
	}
}


你可能感兴趣的:(match,匹配,括号,Braces)