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;
}
蒟蒻一只, 欢迎大佬们批评指正