题目:
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.
Subscribe to see which companies asked this question
方法1代码(动态规划):
class Solution {
public:
int longestValidParentheses(string s) {
int maxlen = -1;
int size = s.size();
if (size <= 1)return 0;
vector<int>dp(size,0);
for (int i = 0; i < size;i++){
if (s[i] == '(')dp[i] = 0;
else{//如果是右括号
if (i-1>=0&&s[i-1]=='('){
dp[i] = 2;
if (i-2>=0&&dp[i-2]!=0){//连接,类似于((()))()
dp[i] = dp[i - 2] + 2;
}
}
else if(i-1>=0&&s[i-dp[i-1]-1]=='('){//类似于(((())))
dp[i] = dp[i - 1] + 2;
if (dp[i - dp[i]] != 0){//连接,类似于()((()))
dp[i] = dp[i]+dp[i - dp[i]];
}
}
else dp[i] = 0;
}
if (dp[i] > maxlen)maxlen = dp[i];
}
return maxlen;
}
};
Submission Result: Accepted More Details
Share your acceptance!
这种方法最关键的是dp[i]不等于0的时候,如果dp[i]=k则表示包含第i个括号在内一共用k个括号匹配,当出现‘(’,dp[i]=0;
如果出现右括号')',则进行如下判断
1.是否和它前一个括号成对,如果成对,则当前dp[i]=2,;连接操作,如果出现((()))()情况,那还要将前面的四个括号()()连接起来,则此时的长度为6;
2.虽然和前面一个括号不匹配,但是可能和前面的某一个匹配,例如这种情况(((())));
3.和它前面一个匹配成功,但是要和前面已经匹配的括号进行连接,类似这种情况()((()));
方法2(利用栈的思想):
class Solution {
public:
int longestValidParentheses(string s) {
int maxlen = -1;
int size = s.size();
if (size <= 1)return 0;
s.insert(s.begin(),'#');
s.push_back('#');
size += 2;
vector<pair<char, int>>stk;
for (int i = 0; i < size; i++){
if (s[i] == '#')stk.push_back(make_pair('#', i));
else if (s[i] == '(')stk.push_back(make_pair('(', i));
else{//放进去的是右括号)
if (stk[stk.size() - 1].first == '(')stk.pop_back();
else stk.push_back(make_pair(')', i));
}
}
if (stk.size() == 1)return size - 1;
for (int i = 1; i < stk.size(); i++){
int temp = stk[i].second -stk[i - 1].second - 1;
if (temp>maxlen)maxlen = temp;
}
return maxlen;
}
};
Submission Result: Accepted More Details
Share your acceptance!
分析:用栈的思想来检测括号是否匹配是以一种传统的思想,这种做法能够检测出所有匹配的括号,所有不匹配的括号将会留在栈里面,如下图:
测试的括号序列为str="#((((()))#"
我们可以看str中从序号3开始匹配一直到8,这样只要我们计算每一段的差值并找出最大的那个就可以算出最长的匹配符号串!!!!!