1.思路
括号匹配问题,首先有一个待匹配的字符串(一串括号)和一个栈(后进先出),一直判断是否有待匹配括号(有左压入栈,有右就匹配):
一:有。判断栈是否为空:
(一)空。匹配失败。
(二)非空。
---------判断待匹配括号左右,
---------左:压入栈;
---------右:与栈内括号进行匹配(成功true失败false)。
二:没有。判断栈是否为空(一)空。匹配成功。(二)非空。匹配失败。
2.代码实现
#include<cstdio>
#include<stack>
using namespace std;
bool Bracket_check ( char str[], int length ){//传入待匹配括号和其个数
stack < char > st;//STL标准模板库
for ( int i = 0; i < length; i++ ){//for循环实现判断是否还有待匹配括号
if ( str[i] == '(' || str[i] == '[' || str[i] == '}' )
st.push ( str[i] );//有且为左括号压入栈
else{
if ( st.empty() )//没有,判断栈空否
return false;
char topelem = st.top();//注意st.pop不返回值
st.pop();//需要返回值要和top连用
if ( str[i] == ')' && topelem != '(')
return false;
if ( str[i] == ']' && topelem != '[')
return false;
if ( str[i] == '}' && topelem != '{')
return false;
}
}
return st.empty();//最后无待匹配且栈也为空,即匹配成功
}
int main()
{
char str[11] = "()(())";//字符串最后位置有'\0'
printf("%s\n\n",str);
if ( Bracket_check ( str, 6 ) )
//注意传入参数一定是待匹配括号个数,不能多不能少
printf( "匹配成功!");
else
printf ( "匹配失败!");
}