[LeetCode] Longest Valid Parentheses 最長有效括號

Grandyang發表於2015-04-14

 

Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.

Example 1:

Input: "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()"

Example 2:

Input: ")()())"
Output: 4
Explanation: The longest valid parentheses substring is "()()"

 

這道求最長有效括號比之前那道 Valid Parentheses 難度要大一些,這裡我們還是藉助棧來求解,需要定義個start變數來記錄合法括號串的起始位置,我們遍歷字串,如果遇到左括號,則將當前下標壓入棧,如果遇到右括號,如果當前棧為空,則將下一個座標位置記錄到start,如果棧不為空,則將棧頂元素取出,此時若棧為空,則更新結果和i - start + 1中的較大值,否則更新結果和i - 棧頂元素中的較大值,程式碼如下:

 

class Solution {
public:
    int longestValidParentheses(string s) {
        int res = 0, start = 0;
        stack<int> m;
        for (int i = 0; i < s.size(); ++i) {
            if (s[i] == '(') m.push(i);
            else if (s[i] == ')') {
                if (m.empty()) start = i + 1;
                else {
                    m.pop();
                    res = m.empty() ? max(res, i - start + 1) : max(res, i - m.top());
                }
            }
        }
        return res;
    }
};

 

還有一種利用動態規劃Dynamic Programming的解法,可參見網友喜刷刷的部落格

 

類似題目:

Remove Invalid Parentheses

Different Ways to Add Parentheses

Generate Parentheses

Valid Parentheses

 

參考資料:

https://leetcode.com/problems/longest-valid-parentheses/

 

LeetCode All in One 題目講解彙總(持續更新中...)

相關文章