- 括弧的匹配
#include <iostream>
#include <stack>
#include <string>
using namespace std;
void match(string& str)
{
stack<char> s;
s.push(str[0]);
for (int i = 1; i < str.size(); i++)
{
//这一层考虑 ()) 的情况
if (s.empty())
{
s.push(str[i]);
}
else
{
//如果匹配就出栈 判断是否匹配的关键
if ((s.top() == '(' && str[i] == ')') || (s.top() == '[' && str[i] == ']')
|| s.top() == '{' && str[i] == '}')
{
s.pop();
}
else
{
s.push(str[i]);
}
}
}
if (s.empty())
{
cout << "匹配成功!" << endl;
}
else
{
cout << "匹配不成功!" << endl;
}
}
int main()
{
string str = "{()[[]]}";
match(str);
return 0;
}
思路:可以用栈的知识解决。利用栈先进后出的特征解决此题
主要流程如下: 以"{()[[]]}"为例
先将{存入栈中,进入循环发现(与{不匹配那么(也入栈,进入下一循环发现 ( 与 )相匹配那么(出栈进入下一次循环… …