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.

 

这 道题是求最长的括号序列,比较容易想到用栈这个数据结构。基本思路就是维护一个栈,遇到左括号就进栈,遇到右括号则出栈,并且判断当前合法序列是否为最长 序列。不过这道题看似思路简单,但是有许多比较刁钻的测试集。具体来说,主要问题就是遇到右括号时如何判断当前的合法序列的长度。比较健壮的方式如下:
(1) 如果当前栈为空,则说明加上当前右括号没有合法序列(有也是之前判断过的);
(2) 否则弹出栈顶元素,如果弹出后栈为空,则说明当前括号匹配,我们会维护一个合法开始的起点start,合法序列的长度即为当前元素的位置 -start+1;否则如果栈内仍有元素,则当前合法序列的长度为当前栈顶元素的位置下一位到当前元素的距离,因为栈顶元素后面的括号对肯定是合法的,而 且左括号出过栈了。

因为只需要一遍扫描,算法的时间复杂度是O(n),空间复杂度是栈的空间,最坏情况是都是左括号,所以是O(n)。实现的代码如下:

  1. public int longestValidParentheses(String s) {  
  2.     if(s==null || s.length()==0)  
  3.         return 0;  
  4.     LinkedList<Integer> stack = new LinkedList<Integer>();  
  5.     int start = 0;  
  6.     int max = 0;  
  7.     for(int i=0;i<s.length();i++)  
  8.     {  
  9.         if(s.charAt(i)=='(')  
  10.         {  
  11.             stack.push(i);  
  12.         }  
  13.         else  
  14.         {  
  15.             if(stack.isEmpty())  
  16.             {  
  17.                 start = i+1;  
  18.             }  
  19.             else  
  20.             {  
  21.                 stack.pop();  
  22.                 max = stack.isEmpty()?Math.max(max,i-start+1):Math.max(max,i-stack.peek());  
  23.             }  
  24.         }  
  25.     }  
  26.     return max;  
  27. }  

这种用剩余栈的栈顶元素位置信息作为当前合法数据的判断依据是比较重要的技巧,在Largest Rectangle in Histogram这道题里面也用到了,有兴趣的朋友可以看看哈。

 

 

class Solution {
public:
    int longestValidParentheses(string s) {
        stack<int> st; // bookkeeping the index of unmatched '('
        int result = 0, accu = 0;
        
        for (int i = 0; i < s.size(); i++) {
            if (s[i] == '(') {
                st.push(i);
            }
            else if (s[i] == ')') {
                if (st.empty()) {  // extra ')', start anew
                    accu = 0;
                }
                else {
                    int j = st.top();
                    st.pop();
                    if (st.empty()) { // no unmatched '(' in the left
                        accu += i - j + 1;
                        result = max(accu, result);
                    }
                    else {
                        // all the chars after st.top() have been matched
                        result = max(result, i - st.top());
                    }
                }
                
            }
            // else continue
        }
        
        return result;        
    }
};

 

posted on 2015-01-08 16:42  风云逸  阅读(48)  评论(0)    收藏  举报