码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode-32-Longest Valid Parentheses]

时间:2017-06-18 18:08:00      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:turn   ann   put   match   ace   mat   ide   long   idp   

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.

思路

The workflow of the solution is as below.

    1. Scan the string from beginning to end.
    2. If current character is ‘(‘,
      push its index to the stack. If current character is ‘)‘ and the
      character at the index of the top of stack is ‘(‘, we just find a
      matching pair so pop from the stack. Otherwise, we push the index of
      ‘)‘ to the stack.
    3. After the scan is done, the stack will only
      contain the indices of characters which cannot be matched. Then
      let‘s use the opposite side - substring between adjacent indices
      should be valid parentheses.
    4. If the stack is empty, the whole input
      string is valid. Otherwise, we can scan the stack to get longest
      valid substring as described in step 3.
 int longestValidParentheses(string s) 
    {
      stack<int>st;
      if(s.length()<=1)return 0;
      
      for(int i=0;i<s.length();i++)
      {
    if(st.empty())st.push(i);
    else 
    {
      if(s[i] ==()st.push(i);
      else if(s[i]==)&&s[st.top()]==()st.pop();
      else st.push(i);      
    }
      }
      if(st.empty()) return s.length();
      
      int a =s.length(),b =0;
      int longest = 0;
      while(!st.empty())
      {
    b=st.top();
    st.pop();
    longest = max(longest,a-b-1);
    a = b;
      }
      longest = max(longest,a);
      return longest;
    }

参考:

https://discuss.leetcode.com/topic/2289/my-o-n-solution-using-a-stack

[leetcode-32-Longest Valid Parentheses]

标签:turn   ann   put   match   ace   mat   ide   long   idp   

原文地址:http://www.cnblogs.com/hellowooorld/p/7044761.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!