POJ-1400(删除冗余括号)

题目:http://poj.org/problem?id=1400

一开始在判断括号内是否全是乘或除时忘了括号内还有括号的情况,WA了两次之后找到了数据,对比答案之后才发现这个问题……删括号规则:

(1)括号前是除号,不能删

(2)括号前是乘号或减号,如果括号内全是乘除法或者被括号括起来的运算

(3)括号前是加法,如果括号后面是加法、括号后面是减法、括号内全是乘除法或者被括号括起来的运算


#include 
#include 
using namespace std;

inline bool isOperator(char c){
    return c == '+' || c == '-' || c == '*' || c == '/';
}
bool allMulOrDiv(const string& exp)
{
    for(int i = 0, len = exp.size(); i < len; ++i){
        if(exp[i] == '('){
            int cnt = 1;
            for(++i; true; ++i){
                if(exp[i] == '(') ++cnt;
                else if(exp[i] == ')'){
                    --cnt;
                    if(!cnt) break;
                }
            }
            ++i;
        }
        if(exp[i] == '+' || exp[i] == '-') return false;
    }
    return true;
}
int findMatchedLeft(const string& exp, int r)
{
    int countOfRight = 1;
    for(--r; r >= 0; --r){
        if(exp[r] == ')') ++countOfRight;
        else if(exp[r] == '('){
            --countOfRight;
            if(!countOfRight) break;
        }
    }
    return r;
}
string& simplify(string& exp)
{
    int left, right = 0;
    char head, tail, can;
    while((right = exp.find(')', right)) != string::npos){
        left = findMatchedLeft(exp, right);
    //get info
        if(left && isOperator(exp[left-1])) head = exp[left-1];
        else head = '+';
        if(right+1 < exp.size() && isOperator(exp[right+1])) tail = exp[right+1];
        else tail = '+';
    //analyze
        if(right - left == 2) can = 1;
        else if(head == '/') can = 0;
        else if(head == '*' || head == '-') can = allMulOrDiv(exp.substr(left+1, right-left-1));
        else can = tail == '+' || tail == '-' || allMulOrDiv(exp.substr(left+1, right-left-1));
    //process
        if(can){
            exp.erase(left, 1).erase(right - 1, 1);
            --right;
        }
        else ++right;
    }

    return exp;
}

int main()
{
    ios::sync_with_stdio(false);
    int test;
    cin >> test;
    while(cin.get() != '\n') cin.get();
    string exp;
    while(test--){
        getline(cin, exp);
        cout << simplify(exp) << "\n";
    }
    return 0;
}

你可能感兴趣的:(每天A一道题,字符串)