从今天2017.10.15开始记录我的leetcode被虐之旅
毫无疑问,这又是一道凭借我一己之力无法解出的题,并且难度分级是hard级别,我也选择这道题作为我学习DP(Dynamic Programming)的开始吧!
动态规划的一般是从解决小问题开始,选择自底向上(迭代)或者自顶向下(递归)解决问题
而关键问题就是求出状态转移方程
题目描述如下:
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.
由此可以构建一个longest[]数组记录对应下标位置的最长有效括号长度
1. 可知当前s[i] == ‘(‘时,longest[i] = 0;
2. 当s[i] == ‘)’时longest数组才可更新:
此时说明可以找到左括号与当前右括号进行匹配,最后面加上的是匹配位置之前的最长括号长度
if s[i - 1] == ')' and s[i - longest[i-1] - 1] == '(' :
longest[i] = longest[i-1] + 2 + longest[i-longest[i-1]-2]
最后代码呈现如下:
int longestSubParentheses(string s){
if (s.length() <= 1)
return 0;
//这样初始化,定义了以i下标结尾的最长括号串
vector<int> longest(s.length(), 0);
int curMax = 0;
for (int i = 1; i < s.length(); i++)
if (s[i] == ')' && s[i - longest[i - 1] - 1] == '(' && i - longest[i - 1] - 1 >= 0)
{
longest[i] = longest[i - 1] + 2 + (i - longest[i - 1] - 2) >= 0 ? longest[i - longest[i - 1] - 2] : 0;
curMax = max(curMax, longest[i]);
}
return curMax;
}