zoukankan      html  css  js  c++  java
  • 动态规划--合法括号字段

    题目来源:51node 1791

    题意:找出合法子字符串的个数,先找出每个‘(’对应的‘)’位置,从后往前扫求和。

    代码:

    /*****************************************************
    *Author:chenxi
    *method: s[i]如果是'(',那么pos[i]代表的是与之匹配到的')'位置 
    *dp[pos[i]]代表的是合法字符串的数目,从n到i的合法字符串个数 
    *dp[i] = dp[pos[i]+1]+1 
    *
    ******************************************************/
    #include <iostream>
    #include <string.h>
    #include <string>
    #include <cstdio>    
    #include <stack>
    using namespace std;
    typedef long long ll;
    const int maxn = 1100005;
    
    ll dp[maxn],pos[maxn];
    //string s;
    char s[maxn];
    ll sum = 0;
    int main()
    {
        ll t;
        scanf("%lld",&t);
        while(t--){
            sum = 0;
            scanf("%s",s);
            int len = strlen(s);
            stack<int> kuohao;  //'('
            for(int i = 0;i <= len;++i){
                pos[i] = -1;
                dp[i] = 0;
            }
            for(int i = 0;i < len;++i){
                if( s[i]=='(' ) kuohao.push(i);
                else{
                    if( !kuohao.empty() ){
                        pos[kuohao.top()] = i;
                        kuohao.pop();
                    }
                
                } 
            }
            for(int i = len-1;i >= 0;--i){
                if( pos[i]==-1 ) continue;
                dp[i] = dp[pos[i]+1]+1;
                sum += dp[i];
            }
        printf("%lld
    ",sum);
        }
        return 0;
    }
  • 相关阅读:
    49 我素故我在
    91 棋盘游戏
    55 删除数组重复元素
    54 删除数组元素
    C++虚函数, 纯虚函数
    iOS-OC-多态
    C++函数引用形参和非引用形参
    怎么清理Mac 硬盘里的其他
    Vue.js中this.$nextTick()的使用
    data中有嵌套,取值要链式取
  • 原文地址:https://www.cnblogs.com/chenxi0x0/p/9720326.html
Copyright © 2011-2022 走看看