[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; }};