[LeetCode] Longest Valid Parentheses,validparentheses

來源:互聯網
上載者:User

[LeetCode] Longest Valid Parentheses,validparentheses

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.

解題思路:

題意找到最長有效括弧的子串長度。求最大問題,第一想法就是動態規劃,但是,通項公式真不好找。喜刷刷http://bangbingsyb.blogspot.jp/2014/11/leetcode-longest-valid-parentheses.html中有相關說明,我沒有理解,。

由於是括弧問題,可以用棧來實現。這跟判斷棧是否有效不同。注意到,若某個右括弧不與前面的某個左括弧匹配,那麼,這個右括弧可以作為子串分割標記。大體思想是,若遇到左括弧,無條件將左括弧的下標入棧。若遇到右括弧,若棧頂是左括弧與之匹配,將左括弧出棧,更新最大的長度值。若棧頂沒有左括弧與之匹配,將該右括弧的下標入棧,作為分割字元。代碼如下:

class Solution {public:    int longestValidParentheses(string s) {        int len=s.length();                stack<int> st;                int maxLen=0;                for(int i=0; i<len; i++){            if(s[i]=='('){                st.push(i);            }else{                if(!st.empty()&&s[st.top()]=='('){                    st.pop();                    maxLen = max(maxLen, st.empty()?i+1:i-st.top());                }else{                    st.push(i);                }            }        }                return maxLen;    }};


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.