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.
找到正确的最长括号串长度。
先来看我的愚蠢的N^3解法:
1 bool isValid(string s) { //判断一个字串是不是配对的括号序列 2 vector<char> stack; 3 int len = s.length(); 4 for(int i = 0 ;i < len; i++){ 5 if(stack.empty()){ 6 stack.push_back(s[i]); 7 } 8 else if((stack.back()==‘(‘ && s[i] == ‘)‘)){ 9 stack.pop_back(); 10 } 11 else{ 12 stack.push_back(s[i]); 13 } 14 } 15 if(stack.empty()){ 16 return true; 17 } 18 else 19 return false; 20 } 21 22 int longestValidParentheses(string s) { 23 if(s.length()<=1){ 24 return 0; 25 } 26 vector<int > leftParentheseIndex; 27 for(int i = 0 ;i< s.length();i++){ 28 if(s[i]==‘(‘){ 29 leftParentheseIndex.push_back(i);//找到所有"("的索引 30 } 31 } 32 int longestLength=-1; 33 for(int i = 0 ; i< leftParentheseIndex.size() ;i++){//对于每一个从"("开始的穿,找它所有的字串,看是不是有效地括号序列,记录最大长度 34 for(int j=leftParentheseIndex[i]+1; j<s.length(); j+=2 ){ 35 if(isValid(s.substr(leftParentheseIndex[i],j-leftParentheseIndex[i]+1))){ 36 if(j-leftParentheseIndex[i]+1>longestLength){ 37 longestLength = j-leftParentheseIndex[i]+1; 38 } 39 } 40 } 41 if(longestLength>=s.length()-leftParentheseIndex[i]){ 42 break; 43 } 44 } 45 return longestLength; 46 }
这个方法就不说了,要多蠢有多蠢,绝对的超时,因为重复计算了茫茫多的字串。
看看别人的方法:
1 int longestValidParentheses(string s) 2 { 3 stack<int>S; //维护一个存放括号索引的栈,栈底存放上一次不匹配发生的位置 4 S.push(-1); 5 int ans=0; 6 for(string::size_type i=0;i<s.size();i++) 7 { 8 //printf("%d\n",S.size()); 9 char ch=s[i]; 10 if(ch == ‘(‘) //存入遇到的所有"("的索引 11 { 12 S.push(i); 13 } 14 else 15 { 16 if(S.size()>1) //如果是")"而且栈内有"("的索引,说明有可以消除的括号对 17 { 18 S.pop(); //消除那对括号即弹出"("的索引 19 int tmp=S.top(); //更新最大长度,为当前")"的索引和弹出"("后栈顶 20 ans=max(ans,(int)i-tmp); //元素的差 和 当且结果之间的最大值 21 } 22 else //若栈内没有"("的索引,说明无法匹配,更新栈底的数据位当前索引 23 { 24 S.pop(); 25 S.push(i); 26 } 27 } 28 } 29 return ans; 30 }
我怎么只能想到这么蠢得方法 T^T。
LeetCode 32 Longest Valid Parentheses
原文:http://www.cnblogs.com/yang-xiong/p/4957865.html