正則問題
題目
考慮一種簡單的正則表達式:
只由 x ( ) | 組成的正則表達式。
小明想求出這個正則表達式能接受的最長字符串的長度。
例如 ((xx|xxx)x|(x|xx))xx 能接受的最長字符串是: xxxxxx,長度是6。
輸入格式
一個由x()|組成的正則表達式。
輸出格式
輸出所給正則表達式能接受的最長字符串的長度。
數據範圍
輸入長度不超過100,保證合法。
輸入樣例
((xx|xxx)x|(x|xx))xx
輸出樣例
6
題解
思路
#include <iostream>
using namespace std;
string str;
int k;
int dfs() {
int res = 0;
while (k < str.size()) {
if (str[k] == '(') {
k ++;
res += dfs();
k ++;
}
else if (str[k] == '|') {
k ++;
res = max(res, dfs());
}
else if (str[k] == ')') break;
else
res ++, k ++;
}
return res;
}
int main () {
cin >> str;
cout << dfs();
return 0;
}