AcWing 1225. 正则问题

原题链接

考察:搜索

思路:

        这道题不需要找根,从头到尾搜索即可.因为最外层括号一定是最外层的递归,搜里层括号相当于搜索叶子结点.当搜索到|说明左结点已经搜索完毕,应当搜索右节点,而右节点也想当一个二叉树.直接dfs即可.这里的dfs不需要变量,因为不需要回溯.

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <cstring>
 4 #include <stack>
 5 using namespace std;
 6 const int N = 110;
 7 char s[N];
 8 int len,pos;
 9 int dfs()
10 {
11     int res = 0,maxn = 0;
12     while(pos<len)
13     {
14         if(s[pos]=='(') pos++,res+=dfs();
15         else if(s[pos]=='x') pos++,res++;
16         else if(s[pos]=='|')
17         {
18             pos++;
19             maxn = res;
20             res = 0;
21         }else if(s[pos]==')')
22         {
23             pos++;
24             maxn = max(res,maxn);
25             return maxn;
26         }
27     }
28     maxn = max(res,maxn);
29     return maxn;
30 }
31 int main()
32 {
33     scanf("%s",s);
34     len = strlen(s);
35     int ans = dfs();
36     printf("%d\n",ans);
37     return 0;
38 }

 

posted @ 2021-02-28 21:36  acmloser  阅读(63)  评论(0编辑  收藏  举报