P8650 [蓝桥杯 2017 省 A] 正则问题

可以把这道题看成一个只有 一种运算符的表达式求值

#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <string>
#define For(i, j, n) for(int i = j ; i <= n ; ++i)
using namespace std;

string str;
int step, len, cnt;
int get_len();
int get_primary();

int get_primary()
{
    
    //cout << "1 " << step << endl;
    if(str[step] == '(')
    {
        step++;
        int ans = get_len();
        //cout << "done " << step << endl;
        step++;
        return ans;
    }
    if(str[step] == 'x')
    {
        //cout << "x at" << step << endl;
        int k = step;
        while(str[k] == 'x')
            k++;
        int ans = k - step;
        step = k;
        //cout << "1 ends at" << step << endl;
        return ans;
    }
    return 0;
}

int get_len()
{
    
    //cout << "2 " << step << endl;
    int ans = 0;
    ans += get_primary();
    while(1)
    {
        if(str[step] == '|')
        {
            step++;
            ans = max(ans, get_len());
        }
        else if(str[step] == '(' || str[step] == 'x') 
            ans += get_primary();
        else
            break;
    }
    return ans;
}

int main()
{
    cin >> str;
    len = str.length();
    cout << get_len();
    return 0;
}

 极简写法:

#include<bits/stdc++.h>
using namespace std;
int dfs(){
    char c;
    int s=0;
    while(cin>>c){
        if(c=='x') s++; //长度加1
        else if(c=='(') s+=dfs(); //调用函数计算子正则表达式的长度。
        else if(c==')') return s; //返回当前长度
        else return max(s,dfs());//调用函数,返回返回值与当前长度中较大的那一个
    }
    return s;//返回当前长度
}
int main(){
//    freopen(".in","r",stdin);
//    freopen(".out","w",stdout);
    printf("%d",dfs());
    return 0;
}

 

posted @ 2024-01-17 17:30  Gold_stein  阅读(2)  评论(0编辑  收藏  举报