[leetcode] 【棧】 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.

題意

判斷一個只包含“(”    “)”的字符串,其符合規則的最長連續有效長度是多少。

題解

難度在於判斷從哪裏開始計算有效字符的長度,比如()(()()   正確的長度是4,難度在於如何知道最長的有效字符在第四個字符開始。


所以用棧存儲的不應該是字符,而是該字符的下標。

當遇到)沒有匹配的(時,應該把起始座標改爲)的下標。    當一對()匹配完(此時匹配的‘(’已經出棧),而stk還沒空的話,那麼有效長度暫時是i-stk.top()。

代碼應該會比較清晰。

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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章