历届试题 正则问题【递归】

问题描述
  考虑一种简单的正则表达式:
  只由 x ( ) | 组成的正则表达式。
  小明想求出这个正则表达式能接受的最长字符串的长度。

  例如 ((xx|xxx)x|(x|xx))xx 能接受的最长字符串是: xxxxxx,长度是6。
输入格式
  一个由x()|组成的正则表达式。输入长度不超过100,保证合法。
输出格式
  这个正则表达式能接受的最长字符串的长度。
样例输入
((xx|xxx)x|(x|xx))xx
样例输出
6
题目分析
处理好遇到每一种字符的情况即可。
#include <cstdio>
#include <iostream>
#include <stack>
#include <algorithm>
#include <time.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
char s[10000];
int i = 0;
int num = 0;
int dfs() {
    int n = 0;
    int m = 0;
    char c = 'a';
    while (c != '') {
        c = s[i++];
        if (c == 'x')
            n++;
        else if (c == '|') {
            m = max(n, m);
            n = 0;
        }
        else if (c == ')') {
            m = max(n, m);
            return m;
        }
        else if (c == '(')
            n += dfs();
    }
    return max(n, m);
}
int main() {
    scanf("%s", s);
    num = dfs();
    cout << num;
    return 0;
}
原文地址:https://www.cnblogs.com/woxiaosade/p/10494918.html