题目:
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.
大意是寻找字符串里面 "()"匹配最长的长度。最直接的思路是遍历字符串,如果是 '(',则判断下一个字符是否是 ')',如果是,则继续向下判断,同时记录当前最长的字符长度。思路比较直接。时间复杂度:O(n)。
int longestValidParentheses(string const& s)//Longest Valid Parentheses { int i=0; int length=s.length();//字符串长度 int long_length=0,max=0; while(i<length)//遍历字符串 { if(s[i]=='(')//找到前(,判断后面一个是否为) { if(s[i+1]==')')//满足 { i=i+2; long_length=long_length+2; if(max<long_length) max=long_length;//记录字符串长度 } else//不是),继续查找 { i=i+1; long_length=0; } } else //是),但是不配,过滤 { i=i+1; long_length=0; } } return max; }