leetcode Longest Valid Parentheses

2014-11-24 00:43:45 · 作者: · 浏览: 3
The stack has to record the last position of '('. If matching, The position of ')' - the position of '(' + 1 is the answer since the parentheses between them have been eliminated.
class Solution {  
 public:  
  int longestValidParentheses(string s) {  
    // Note: The Solution object is instantiated only once and is reused by each test case.  
    stack sta;  
    int i = 0, j = 0, maxV = 0, count = 0;  
    for (i = 0; i < s.length(); ++i) {  
      if (s[i] == '(')  
        sta.push(i);  
      else {  
        if (!sta.empty() && s[sta.top()] == '(') {  
          sta.pop();  
          if (sta.empty())  
            count = i + 1;  
          else  
            count = i - sta.top();  
          if (count >
maxV) maxV = count; } else sta.push(i); } } return maxV; } };