32. 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.

分析

尋找一個只有'('和')'的字符串中有效的匹配括號對的最長長度,用一個棧記錄未匹配的'('或')'的下標,當字符串中出現一個能匹配的括號對時,彈出棧頂下標,此時的棧頂下標是最後一個未匹配的字符下標,用i-st.top()算出此時連續匹配的最長長度,並跟maxL比較得到最長的長度。

例如,對")()())",當第一個括號對匹配時,st.top()=0,i=2,此時maxL=2,當第二個括號對匹配時,st.top()=0,i=4,此時maxL=4;對"(()(()",當第一個括號對匹配時,st.top()=0,i=2,此時maxL=2,當第二個括號對匹配時,st.top()=3,i=5,此時maxL=2。可以看出,由於連續匹配的括號對下標彈棧,所以i-st.top()可以得到當前所在的匹配括號長度,如果中途該匹配串中斷了,則再次計算時,st.top()記錄的是新的匹配括號串前一個元素的下標,仍可作爲長度來計算,並實時更新maxL值。

class Solution {
public:
    int longestValidParentheses(string s) {
        stack<int> st;//用棧記錄下字符串中未匹配成對的'('和')'出現的位置
        st.push(-1);
        int size=s.size();
        int maxL=0;//記錄最長的匹配串長度
        for(int i=0;i<size;++i){
            int t=st.top();
            if(t!=-1&&s[t]=='('&&s[i]==')'){//如果當前字符與棧頂字符匹配成一對,則將棧頂元素彈出,並計算此時已匹配的最長長度
                st.pop();
                maxL=max(maxL,i-st.top());
            }
            else
                st.push(i);//否則將當前字符的下標壓入棧
        }
        return maxL;
    }
};


發佈了180 篇原創文章 · 獲贊 15 · 訪問量 18萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章