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