#include<iostream>
using namespace std;
//括号匹配问题
bool Match(const char* exp) {
if (exp == NULL) return false;
int i = 0;
int len = strlen(exp);
char* _Stack = (char*)malloc(sizeof(char) * len);
int top = 0;
while (exp[i] != '\0') {
if (exp[i] == '{' || exp[i] == '(' || exp[i] == '[') {
_Stack[top] = exp[i];
top++;
}
else if (exp[i] == '}') {
top--;
if (_Stack[top] != '{')return false;
}
else if (exp[i] == ']') {
top--;
if (_Stack[top] != '[')return false;
}
else if (exp[i] == ')') {
top--;
if (_Stack[top] != '(')return false;
}
i++;
}
if (top != 0) return false;
return true;
}
int main() {
char str[] = { "()[" };
if (Match(str)) {
cout << "字符串匹配!" << endl;
}
else cout << "字符串不匹配!" << endl;
}
总结:
1.使用栈结构不一定需要完全入栈,灵活运用,本次的判断算法即为部分入栈,即左边的括号入栈,利用右边未入栈的括号进行判断与计算。
2.同时,在解部分较为困难的问题时,可以考虑查表法,如atoi函数在使用查表法时较为方便。