C++ 数据结构 括号匹配问题

Description

  • There is an expression with three kinds of brackets () [] {}. For example ([(#+#)*(#+#)] {(……)}). Maybe the format of the expression is incorrect such as [()[)…((, ({}(…), ([])(, {[{}})))), ]([([(. (the brackets have been put with wrong positions)
  • Design an algorithm for checking the format of the expression with brackets.
  • If the format of the expression is correct then the function return true.
  • If the format of the expression is incorrect then the function return false.

translation:

  • 有一个表达式有三种括号()[]{}。例如([(#+#)*(#+#)]{(…)})。 可能表达式的格式不正确,例如[()[)…(,({}(…),([])(,{[{}})),]([([()。(括号放错了位置)
  • 设计了一种带括号的表达式格式检查算法。
  • 如果表达式的格式正确,则函数返回true。
  • 如果表达式的格式不正确,则函数返回false。

Algorithm

#include <iostream>
#include <string>
#include <stack>	

using namespace std;

/*设置一个bool型函数对表达式中括号是否正确进行检查*/ 
bool fun(string str)
{
	stack<char> s;								//创建一个成员为字符的栈 s; 
	char c;										//创建一个用来存放出栈左括号的字符变量c; 
	for(int i=0; i<str.size(); i++)				//遍历表达式字符串; 
	{								
		if (str[i] == '('||str[i] == '['||str[i] == '{') //如果是左括号,进行压入栈顶 
			s.push(str[i]);
		else if (str[i] == ')'||str[i] == ']'||str[i] == '}') {	//如果是右括号,进行判断; 
			if (s.empty()) return false;		//如果栈空,说明没有左括号可以匹配,返回false; 
			else {
				c = s.top();					//取出栈顶元素,并放到c中; 
				s.pop();						//弹出栈顶元素; 
				if (!(c == '('&&str[i] == ')'||c == '['&&str[i] == ']'||c == '{'&&str[i] == '}'))
					return false;				//如果c和当前右括号匹配,返回false; 
			}
		}
	}
	if (s.empty()) return true;					//表达式遍历结束后,判断此时栈内是否还有元素,没有则返回true; 
	else return false;							//如果有说明有多余的左括号,返回fasle; 
}

int main()
{
	string str;									//声明存放表达式的字符串; 
	cin >> str;
	if (fun(str)) cout << "Format Correct!\n";	//将表达式字符串作为参数传递给检查是否正确的函数 
	else cout << "Format InCorrect!\n";
	return 0;
} 

蒟蒻一只, 欢迎大佬们批评指正

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值