栈在括号匹配中的应用

栈在括号匹配中的应用

资料推荐

王道考研

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}
字符串中括号匹配

  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

cctv1324

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值