博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode 32. Longest Valid Parentheses
阅读量:4582 次
发布时间:2019-06-09

本文共 1367 字,大约阅读时间需要 4 分钟。

Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.

For "(()", the longest valid parentheses substring is "()", which has length = 2.

Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4.

思路:动态规划思想,括号匹配发生在当前字符s[i]=')'时.

动态规划dp[i]表示以第i个字符为结尾能得到的括号匹配数。

那么在s[i]=')'时发生转移,分两种情况。如果s[i-1]='('那么dp[i]=dp[i-2]+2

如果s[i-1]=')' 并且s[i-dp[i-1]-1]='(' 那么dp[i]=dp[i-dp[i-1]-2] + dp[i-1] + 2
在dp[i]中取最大的即为答案。

注意边界。

代码如下

class Solution {public:    int longestValidParentheses(string s) {        stack 
st; int ans = 0; int tmp = 0; vector
dp(s.size()); for (int i = 1; i < s.size(); ++i) { if (s[i] == ')') { if (s[i-1] == '(') { if (i == 1) dp[i] = 2; else dp[i] = dp[i-2] + 2; } else { if (i < 1) continue; int id = i - dp[i-1] - 1; if (id >=0 && s[id] == '(') { dp[i] = dp[i-1] + 2; if (id >= 1) dp[i] += dp[id-1]; } } } ans = max(dp[i], ans); } return ans; }};

转载于:https://www.cnblogs.com/pk28/p/8619779.html

你可能感兴趣的文章
python全栈学习--day10(函数进阶)
查看>>
Android初学第19天
查看>>
Flask框架web开发
查看>>
LRU算法
查看>>
MongoDB 系列(一) C# 类似EF语法简单封装
查看>>
ios github网址
查看>>
Django 数据库操作之数据库连接
查看>>
写log
查看>>
Python基础 ----- 流程控制
查看>>
选择语言之switch case
查看>>
实现斐波那契神兔
查看>>
Understanding Paxos Algorithm
查看>>
springboot+Zookeeper+Dubbo入门
查看>>
【linux就该这么学】-08
查看>>
JavaScript基础知识汇总
查看>>
PyQt4网格布局
查看>>
PHP学习笔记 - 进阶篇(3)
查看>>
极角排序那些事
查看>>
Ganglia+nagios 监控hadoop资源与报警
查看>>
asterisk事件监控
查看>>