——Longest Valid Parentheses

32、Longest Valid Parentheses

最長有效括號

給定一個僅僅包含'('或 ')'的字符串,找出其中最長有效括號組成的子集的長度。
字符串"(()",它的最長有效號符子集是"()",長度爲2。
另一個例子")()())",它的最長有效括號子集是"()()",長度是4。

分析:

這道題的難點在於,判斷括號有效後,還需要記錄括號的有效長度。
我們使用一個stack來模仿括號的動態變化,一個int類型res記錄長度。
stack的類型爲,一個int記錄括號位置,一個bool表示爲左或右括號(判斷是否匹配)。
遍歷字符串:
1.(:
進棧
2.):
1>棧的前一個元素爲空,進棧
2>棧的前一個元素爲’(‘,匹配則出棧,然後用當前元素位置減去棧頂位置即爲所得長度,然後和res比較。
3>棧的前一個元素爲‘)’,進棧。

代碼:

class Solution {
public:
    class pair//一對
    {
    public:
        int position;//位置
        int FF;//翻轉器
    };
    int longestValidParentheses(string s) {
        stack<pair> stack;
        pair temp;
        temp.position=-1;
        temp.FF=false;
        stack.push(temp);//棧頂添加一個空元素,防止溢出
        int res=0;//字符串長度
        for(int i=0;i<s.length();i++)
            switch(s[i])
            {
                case'('://進棧
                    temp.position=i;
                    temp.FF=true;
                    stack.push(temp);
                    break;
                case')':
                    if(stack.empty())//進棧
                    {
                        temp.position=i;
                        temp.FF=false;
                        stack.push(temp);
                    }
                    else if(stack.top().FF)//出棧
                    {
                        stack.pop();
                        res=max(res,i-stack.top().position);
                    }
                    else//進棧
                    {
                        temp.position=i;
                        temp.FF=false;
                        stack.push(temp);
                    }
                    break;
                default:
                    break;     
            }
        return res;
    }
};



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