藍橋杯-正則問題

藍橋杯-正則問題

解題思路:每次遇到左括號,遞歸處理每一對括號的內容;遇到右括號,須要返回該對括號計算的最終結果.ios


#include<iostream>
#include<cstring>
using namespace std;
int len,pos;
string s;
int f()
{
    int tmp=0,maxx=0;
    while(pos < len)
    {
        if(s[pos] == '(')   //每次遇到左括號,遞歸處理每個括號的內容 
        {
            pos++;
            tmp += f();
        }
        else if(s[pos] == 'x')
        {
            pos++;
            tmp++;
        }
        else if(s[pos] == '|')
        {
            pos++;
            maxx = max(maxx,tmp);
            tmp = 0;
        }
        else if(s[pos] == ')')
        {
            pos++;
            maxx = max(maxx,tmp);
            return maxx;     //遇到右括號,須要返回該對括號計算的結果 
        }
    }
    maxx = max(maxx,tmp);
    return maxx;
}
int main()
{
    cin>>s;
    len = s.length();
    int ans = f();
    cout<<ans<<endl;
    return 0;
}
相關文章
相關標籤/搜索