【LeetCode算法練習(C++)】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.

鏈接:Longest Valid Parentheses
解法:用棧儲存左括號位置,檢查右括號匹配,若匹配則記錄兩者位置之差,即匹配括號長度。時間O(n)

class Solution {
public:
    int longestValidParentheses(string s) {
        int ans = 0;
        stack<int> st;
        st.push(-1);
        for (int i = 0; i < s.length(); i++) {
            if (s[i] == '(') {
                st.push(i);
            } else {
                st.pop();
                if (st.empty()) st.push(i);
                else ans = ans > i - st.top() ? ans : i - st.top();
            }
        }
        return ans;
    }
};

Runtime: 9 ms

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