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

最长的括号子串

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

#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param s string字符串 
# @return int整型
#
class Solution:
    def longestValidParentheses(self , s: str) -> int:
        # write code here
        # 1. loop the string and add the left parenthese into stack: if you pass a right parenthese then 
        # pop one from stack to math this right one. if it has then, length+=2 since it is a pair 
        # if it not has then skipp the length and continue with the loop 
        # "(()"
        # t.e.x stack['(','('] then ), pop one ( from stack and they are matched so length+=2
        # ")()(()()((((((())("  
        #1. [(,] 
        #2. ) len>2
        #3. [(, (]
        #4 matched 4  [(]
        # 5. [(, (]
        #6. mactched 6
        
        # initial DP DP[i] is the max length at index i 
        dp=[0]*len(s)
        maxans=0
        for i in range(1,len(s)):
            if s[i]==')':
                if s[i-1]=='(':
                    if i>=2:
                        dp[i]=dp[i-2]+2
                    else: 
                        dp[i]=2
                else:
                    # then this is type of '...))'
                    if (i-dp[i-1])>0 and s[i-dp[i-1]-1]=='(':
                        if i-dp[i-1] >=2:
                            dp[i] = dp[i-1]+dp[i-dp[i-1]-2] +2
                        else:
                            dp[i] = dp[i-1]+2
                maxans=max(maxans,dp[i])
        return maxans
              
全部评论

相关推荐

不愿透露姓名的神秘牛友
06-26 14:50
人力小鱼姐:有后面墨迹那两句的时间问题早回答完了
点赞 评论 收藏
分享
湫湫湫不会java:1.在校经历全删了2.。这些荣誉其实也没啥用只能说,要的是好的开发者不是好好学生3.项目五六点就行了,一个亮点一俩行,xxx技术解决,xxx问题带来xxx提升。第一页学历不行,然后啥有价值的信息也没有,到第二页看到项目了,第一个项目九点,第二个项目像凑数的俩点。总体给人又臭又长,一起加油吧兄弟
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
06-27 20:15
还能挽救吗?找同学帮忙看了一下 字节怎么能如此对我
牛客26396789...:你这是严重红线,被发现你自己永远进不去,你那个同学直接走人,你还敢宣扬
点赞 评论 收藏
分享
评论
1
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务