栈在括号匹配中的应用
资料推荐
王道考研
3.3.1_栈在括号匹配中的应用_哔哩哔哩_bilibili
代码
我这里直接C++使用标准模板库
包含头文件
#include<iostream>
using namespace::std;
#include<stdint.h>
#include<stack>
#include<string>
函数定义
/*功能:看看括号是否匹配
* 输入:
* str:要检查的字符串
* 返回:
* 匹配 true 不匹配 false
* 其它:无
*/
bool Parenthese_Matching(string& str);
实现
bool Parenthese_Matching(string& str)
{
stack<char> the_stack;
string::iterator p = str.begin();
char tmp = '\0';
while (p != str.end())
{
switch (*p)
{
//左括号就入栈
case '(':
the_stack.push('(');
break;
case '[':
the_stack.push('[');
break;
case '{':
the_stack.push('{');
break;
//右括号看看是否匹配,与入栈的左括号匹配就出栈,不匹配就返回错误
case ')':
tmp = the_stack.top();
if (tmp == '(')
the_stack.pop();
else
return false;
break;
case ']':
tmp = the_stack.top();
if (tmp == '[')
the_stack.pop();
else
return false;
break;
case '}':
tmp = the_stack.top();
if (tmp == '{')
the_stack.pop();
else
return false;
break;
//无视其它字符
default:
break;
}
p++;
}
//检索完成后栈为空,说明括号是匹配的
if (the_stack.size() == 0)
return true;
else
return false;
}
测试一下
//括号匹配问题
void test_1(void)
{
string str1 = "()(){}[]";
cout << "\n\nstr1\n";
cout << str1 << endl;
if (Parenthese_Matching(str1) == true)
cout << "字符串中括号匹配" << endl;
else
cout << "字符串中括号不匹配" << endl;
string str2 = "((){}[]";
cout << "\n\nstr2\n";
cout << str2 << endl;
if (Parenthese_Matching(str2) == true)
cout << "字符串中括号匹配" << endl;
else
cout << "字符串中括号不匹配" << endl;
string str3 = "{()(){}[]}";
cout << "\n\nstr3\n";
cout << str3 << endl;
if (Parenthese_Matching(str3) == true)
cout << "字符串中括号匹配" << endl;
else
cout << "字符串中括号不匹配" << endl;
string str4 = "6+{[5*(1+2)]*8+1}";
cout << "\n\nstr4\n";
cout << str4 << endl;
if (Parenthese_Matching(str4) == true)
cout << "字符串中括号匹配" << endl;
else
cout << "字符串中括号不匹配" << endl;
}
int main(void)
{
test_1();
return 0;
}
结果
str1
()(){}[]
字符串中括号匹配
str2
((){}[]
字符串中括号不匹配
str3
{()(){}[]}
字符串中括号匹配
str4
6+{[5*(1+2)]*8+1}
字符串中括号匹配