LeetCode #32
来源:互联网 发布:2016年年残保金的算法 编辑:程序博客网 时间:2024/05/16 11:01
题目描述:
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.
这道题为hard难度,但是用动态规划就很简单,而且算法效率也很高。
先定义dp数组,定义dp[i]表示以s[i]结尾的最大有效括号匹配的长度。那么对于s[i+1],如果其为左括号,则很明显它不可能作为有效括号匹配的结尾,所以dp[i+1]=0;而当s[i+1]为右括号时,可以进行递推:即设j=i-dp[i],那么s[j]为以s[i]为结尾的最长括号匹配字符串的前一位字符,如果s[j]为右括号,那么它无法和s[i+1]匹配,此时dp[i+1]=0;但是当s[i+1]为左括号时,显然dp[i+1]=2+dp[i],即以s[i]为结尾的最长括号匹配,再加上s[j]和s[i+1],但是还要注意在s[j]之前可能还存在有效的括号匹配,可以直接加入之前得到的括号匹配字符串中,所以dp[i+1]还要加上dp[j-1]。
class Solution {public: int longestValidParentheses(string s) { if(s.empty()) return 0; stack<int> par; int max_length=0; int dp[s.size()]={}; for(int i=0;i<(s.size()-1);i++) { if(s[i+1]=='(') dp[i+1]=0; int j=i-dp[i]; if(s[i+1]==')'&&j>=0) { if(s[j]==')') dp[i+1]=0; if(s[j]=='(') { dp[i+1]=2+dp[i]; if((j-1)>=0) dp[i+1]+=dp[j-1]; } } max_length=max(max_length,dp[i+1]); } return max_length; }};
阅读全文
0 0
- LeetCode #32
- [LeetCode] Subsets II [32]
- LeetCode 32 Triangle
- leetcode #32 in cpp
- Leetcode no. 32
- leetCode练习(32)
- [Leetcode] 71, 32, 84
- LeetCode刷题(32)
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- leetcode
- LEETCODE
- c++ singleton pattern
- kafka0.8版本和sparkstreaming整合的两种不同方式
- 一元多项式求导
- centos安装中文输入法
- 值得推荐的C/C++框架和库 (真的很强大)
- LeetCode #32
- hibernate5控制台打印出sql语句未报错,但是数据库中未创建表
- jmeter脚本报错
- 1026. 程序运行时间(15)
- Java设计模式——外观模式(Facade Pattern)
- jmeter body data乱码
- linux安装中文输入法的命令
- Spring MVC--17.结果返回(3种)
- Spring-boot与maven多环境配置文件设置