当我们遇到一个左括号时,我们就把他压入栈,遇到一个右括号,就把栈顶的左括号出栈,并且检查是否与右括号匹配
当扫描到一个不匹配的,就不用继续往后扫描了,因为不管后面的,这一整个表达式括号肯定是不匹配的
还有一种情况,就是扫描到了右括号,但是栈已经空,这样子就不要在继续扫描了,因为括号肯定不匹配
还有一种情况,就是全部匹配完之后,发现栈里面还有元素,即栈非空,这样子也是不行的
#include#define MaxSize 10 using namespace std; typedef struct { char data[MaxSize]; int top; }SqStack; void InitStack(SqStack& s) { s.top = -1; } bool Empty(SqStack& s) { if (s.top == -1) return true; else return false; } bool push(SqStack& s, char x) { if (s.top == MaxSize - 1) return false; s.top++; s.data[s.top] = x; return true; } bool pop(SqStack& s, char& x) { if (s.top == -1) return false; x = s.data[s.top]; s.top--; return true; } bool pipei(char str[], int length) { SqStack s; InitStack(s); for (int i = 0; i < length; i++) { if (str[i] == '(' || str[i] == '[' || str[i] == '{') { push(s, str[i]); } else {//扫到右括号 if (Empty(s)) { return false; } char topElem; pop(s, topElem); if (str[i] == ')' && topElem != '(') return false; if (str[i] == ']' && topElem != '[') return false; if (str[i] == '}' && topElem != '{') return false; } } return Empty(s); } int main() { char str[] = "((()))"; if (pipei(str, 6)) cout << "匹配" << endl; else cout << "不匹配" << endl; }



