32. Longest Valid Parentheses
来源:互联网 发布:中国临床试验数据库 编辑:程序博客网 时间:2024/06/04 19:38
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.
思路1:stack
我们还是借助栈来求解,需要定义个start变量来记录合法括号串的起始位置,我们遍历字符串,如果遇到左括号,则将当前下标压入栈,如果遇到右括号,如果当前栈为空,则将下一个坐标位置记录到start,如果栈不为空,则将栈顶元素取出,此时若栈为空,则更新结果和i - start + 1中的较大值,否则更新结果和i - 栈顶元素中的较大值,代码如下:
class Solution {public: int longestValidParentheses(string s) { int res = 0, start = 0; stack<int> m; for(int i = 0; i < s.size(); ++i) { if(s[i] == '(') m.push(i); else { if(m.empty()) start = i+1; else { m.pop(); if(m.empty()) res = max(res, i - start + 1); else res = max(res, i - m.top()); } } } return res; }};
思路2:DP
求极值问题一般想到DP或Greedy,显然Greedy在这里不太适用,只有用DP了。
状态:
DP[i]:以s[i]为结尾的longest valid parentheses substring的长度。通项公式:
s[i] = ‘(‘:
DP[i] = 0
s[i] = ‘)’:找i前一个字符的最长括号串DP[i]的前一个字符j = i-1-DP[i-1]
DP[i] = DP[i-1] + 2 + DP[j-1],如果j >=0,且s[j] = ‘(’
DP[i] = 0,如果j<0,或s[j] = ‘)’
- 计算方向
显然自左向右,且DP[0] = 0
class Solution {public: int longestValidParentheses(string s) { int n = s.size(), res = 0; vector<int> dp(n, 0); for(int i = 1; i < n; ++i) { int j = i-1-dp[i-1]; if(s[i] == '(' || j < 0 || s[j] == ')') dp[i] = 0; else { dp[i] = dp[i-1] + dp[j-1] + 2; res = max(res, dp[i]); } } return res; }};
- 32.Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 32. Longest Valid Parentheses
- 一个成功的网站是这样炼成的
- django中的路由规则
- 指针和const
- 位运算相关题目
- Android自定义ViewGroup
- 32. Longest Valid Parentheses
- Java反射
- react-navigation设置navigationOptions中Static中使用this的方法
- 发现一个Fragment没有走FragmentManager的registerFragmentLifecycleCallbacks的情况
- 闵维方、魏新反对王选,罪责难逃!
- Linux文件系统管理、挂载光盘、U盘、移动硬盘,以及手工分区硬盘
- mac 安装opencv/python-opencv
- 动态再次获得权限
- 关于GPRS模块的电源设计经验分享