[LeetCode 解題報告]032. Longest Valid Parentheses

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 "()()"

考察:最大有效括號匹配長度,用棧保存括號的index,如果是'('則壓棧,否則,要判斷棧是否非空纔可以彈出。

class Solution {
public:
    int longestValidParentheses(string s) {
        int res = 0, start = 0;
        stack<int> ss;
        
        for (int i = 0; i < s.length(); i ++) {
            if (s[i] == '(')
                ss.push(i);
            else {
                if (ss.empty())
                    start = i+1;
                else {
                    ss.pop();
                    res = ss.empty() ? max(i-start+1, res) : max(res, i-ss.top());//已經pop了,則不需要+1
                }
            }
        }
        return res;
    }
};

完, 

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