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.
括号匹配,计算最长的括号匹配的字符串,另外如果字符串S1内的括号匹配,字符串s2内的括号匹配,则S1S2应返回s1的长度加s2的长度。
使用栈保存每个字符的下标,进行匹配,计算两下标之间的距离的长度
AC代码
class Solution { public: int longestValidParentheses(string s) { int len=s.size(); stack<int> temp; int max=0; int count=0; for(int i=0; i<len; ++i) { if(s[i]=='(') temp.push(i); else { if(!temp.empty()) { count=temp.top(); if(s[count]==')') temp.push(i); else { temp.pop(); if(temp.empty()) max=i+1; else { count=temp.top(); if(i-count>max) max=i-count; } } } else temp.push(i); } } return max; } };
版权声明:本文为博主原创文章,未经博主允许不得转载。
[leetcode 32]Longest Valid Parentheses
原文地址:http://blog.csdn.net/er_plough/article/details/47183195