LeetCode_Longest Valid Parentheses

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.

  用一个stack来维护上一个未匹配的位置,当出现匹配情况时更新最大值

class Solution {
public:
    int longestValidParentheses(string s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
     
        int n = s.length();
        if(n < 2) return 0;
        
        int maxR = 0 , top,result ;
        stack<int> myS;
        
        for(int i = 0; i < n; i++)
        {
          if(s[i] == '(' || myS.empty())
                myS.push(i);
                
          else 
          {
             top = myS.top();
             if(s[top] == '(')                
             {
                myS.pop();  
                result = myS.empty()? i+1: i - myS.top();
                maxR = maxR > result ? maxR : result ;
            }else   
                myS.push(i);  
             
          }
        }
        
        return maxR;
    }
};

 

posted @ 2013-05-23 23:00  冰点猎手  阅读(206)  评论(0编辑  收藏  举报