Longest Valid Parentheses

来源:互联网 发布:c语言pointer expected 编辑:程序博客网 时间:2024/05/09 00:58

Longest Valid ParenthesesMar 1 '12

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.

和Valid Parentheses的思路差不多,使用stack来进行匹配和消减,最后留在栈里的是没有配对上的index,这样就很容易得到最长valid子串了。

class Solution {public:    int longestValidParentheses(string s) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        stack<int> stack;               for(int i = 0;i < s.length();i++)        {            if(stack.size() != 0 && isMatch(s[stack.top()],s[i]))                stack.pop();            else                  stack.push(i);          }                if(stack.empty()) return s.length();        int long_len = s.length() - stack.top()-1;        while(!stack.empty())        {            int top = stack.top();            stack.pop();            if(!stack.empty())                long_len = max(long_len,top - stack.top()-1);            else                long_len = max(long_len,top);        }        return long_len;    }            bool isMatch(char a,char b)      {          if(a=='(' && b==')') return true;          return false;      }  };

56 milli secs



原创粉丝点击