2480 - D

给你一个由数字,括号和运算符组成的表达式。在这个问题中我们只关心括号。括号有三种形式:"{}","()","[]"。每出现一个左括号,就必须有一个对应的右括号。任意两个括号的作用域之间不能有交集。现在,需要你判断给定的表达式是否合法。

题目输入

一个只由("{}" "()" "[]"),数字,运算符("+" "-" "*" "/")组成的表达式(0<表达式长度<10^3)。

题目输出

合法 True,否则 False。

输入/输出样例

题目输入

((5+3)*2+1)
{[(3+1)+2]+}
(3+{1-1)}
[1+1]+(2*2)-{3/3}
(({[(((1)-2)+3)-3]/3}-3)

题目输出

True
True
False
True
False

C++解答

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <vector>
#include <cstring>
#include <set>
#include <map>
#include <stack>
using namespace std;
stack<char>st;
char p[6]={'{','}','[',']','(',')'};
bool in(char c){
    for(int i=0;i<6;i++)
        if(p[i]==c) return true;
    return false;
}
int main(){
    string s;
    while(cin>>s){
        while(!st.empty()) st.pop();
        for(int i=0;i<s.size();i++){
            if(in(s[i])){
               if(!st.empty()){
                    if(st.top()=='[' && s[i]==']') st.pop();
                    else if(st.top()=='{' && s[i]=='}') st.pop();
                    else if(st.top()=='(' && s[i]==')') st.pop();
                    else st.push(s[i]);
               }
               else st.push(s[i]);
            }
        }
        if(st.empty()) printf("True\n");
        else printf("False\n");
    }
    return 0;
}

时间限制 1 秒
内存限制 128 MB
讨论 统计
上一题 下一题