试题 历届试题 正则问题(思维)


问题描述
  考虑一种简单的正则表达式:
  只由 x ( ) | 组成的正则表达式。
  小明想求出这个正则表达式能接受的最长字符串的长度。
  例如 ((xx|xxx)x|(x|xx))xx 能接受的最长字符串是: xxxxxx,长度是6。
输入格式
  一个由x()|组成的正则表达式。输入长度不超过100,保证合法。
输出格式
  这个正则表达式能接受的最长字符串的长度。
样例输入
((xx|xxx)x|(x|xx))xx
样例输出
6
思路
思维题,挺难的,看题解跟着写的,估计我很快就忘

#include<bits/stdc++.h>
using namespace std;
string str;
int i=0;
int dfs()
{
    int temp=0,maxx=0;
    while(i<str.size()){
        if(str[i]=='x'){
            i++;
            temp++;
        }
        else if(str[i]=='('){
            i++;
            temp+=dfs();//不能直接返回,可能后面是这种情况()|(),要比较
        }
        else if(str[i]==')'){
            i++;
            break;
        }
        else if(str[i]=='|'){
            i++;
            maxx=max(maxx,temp);//记录|之前的长度
            temp=0;
        }
    }
    return maxx=max(maxx,temp);//记录右括号break打断或到结尾最长长度
}
int main()
{
    cin>>str;
    cout<<dfs()<<endl;
    return 0;
}

 

原文地址:https://www.cnblogs.com/mohari/p/12909107.html