栈解决正则问题

用栈解决正则问题:

https://www.acwing.com/problem/content/description/1227/

注意:1.括号中可能有多个 |

2.求max最后还得加上一次

3.count()在主函数中最后要执行一次 ,类似 xxx|xxxx这样的结构可能存在

#include<bits/stdc++.h>
using namespace std;

stack<char> s;
void count(){
    int cnt1=0,maxx=0;
    while(s.size() && s.top()!='('){
        int t=s.top();
        if(t=='x')  cnt1++;
        else{
            maxx=max(maxx,cnt1);   //each time top='|' ,  compare to find maxx
            cnt1=0;
        }
        s.pop();
    }
    maxx=max(maxx,cnt1); //final top is '(', final comparision 
    if(s.size())    s.pop(); //pop (
    for(int j=0;j<maxx;j++) s.push('x');
}
int main()
{
    string str;
    cin>>str;
    for (int i = 0; i < str.size(); i ++ ){
        int t=str[i];
        if(t!=')') s.push(t); //push all symbol except )
        else count();
    }
    
    count();
    cout<<s.size();
    return 0;
}
posted @ 2022-02-25 21:27  秋月桐  阅读(33)  评论(0编辑  收藏  举报