使用栈来实现括号匹配

1.题目:

从标准输入中读取一个文本流并使用栈来判定其中的括号是否配对完整。例如:对于[()]{}{[()()]()} 打印 true;对于 [(]) 打印false。


2.前提:已经定义好栈,只用构造解决函数即可。


solution.hpp


#ifndef SOLUTION_HPP
#define SOLUTION_HPP
#include "stack.hpp"

#include <string>

class Solution
{
public:
	Solution(string str) : data(str){}
	~Solution(){}
	bool getSolution();
private:
	string data;
};

bool Solution::getSolution()
{
	MyStack<char> currentStack;
	int size = data.size();
	bool result = false;

	for (int i = 0; i != size; ++i)        //循环读入字符串
	{	
		/*    如果是左半括号,则压入栈内,如果是右半括号,则弹栈判断是否匹配,不匹配直接返回false,
			如果匹配则继续读入字符判断。
		*/
		switch (data[i])                
		{
			case '(':
				currentStack.push(data[i]);
				break;
			case '[':
				currentStack.push(data[i]);
				break;
			case '{':
				currentStack.push(data[i]);
				break;
			case ')':
				if (currentStack.pop() == '(')
					result = true;
				else
					return false;
				break;
			case ']':
				if (currentStack.pop() == '[')
					result = true;
				else
					return false;
				break;
			case '}':
				if (currentStack.pop() == '{')
					result = true;
				else
					return false;
				break;
			default:
				break;
		}
	}

	return result;
}

#endif


main.cpp

#include "solution.hpp"

int main(int argc, char** argv)
{
	Solution solution(argv[1]);
	if (solution.getSolution())
	{
		cout << "true" << endl;
	}
	else
	{
		cout << "false" << endl;
	}
	return 0;
}


3. 关于文件:

i.可以使用跟文件操作相关的流(c++)

ii.可以使用命令行输入(但是要加转义字符很麻烦)

iii.可以使用文件流重定向,管道(待研究)

$ cat input.txt | ./a.out

$ ./a.out < input.txt




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值