题解 | #最长的括号子串#

最长的括号子串

https://www.nowcoder.com/practice/45fd68024a4c4e97a8d6c45fc61dc6ad

using System;
using System.Collections.Generic;


class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param s string字符串 
     * @return int整型
     */
    public int longestValidParentheses (string s) {
        Stack<int> stack = new Stack<int>();
        int res = 0;
        int[] dp = new int[s.Length];
        for(int i = 0; i < s.Length; i++){
            if(s[i] =='(') stack.Push(i);
            if(s[i] ==')' && stack.Count != 0){
                int num = stack.Pop();
                dp[i] = 1;
                dp[num] = 1;
                //Console.WriteLine(i);
                //Console.WriteLine(num);
            }
        }
        for(int i = 0; i < s.Length; i++){
            int cur = 0;
            while(i < s.Length && dp[i] == 1){
                cur++;
                i++;
            }
            res = cur > res ? cur : res;
        }
        return res;
    }
}

全部评论

相关推荐

投递腾讯云智研发等公司7个岗位
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务