leetcode題解32- 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 "()()"


思路:建立棧,存放左括號下標,遇到匹配右括號就出棧,並計算最大匹配個數。


代碼

class Solution {
public:
    //32. Longest Valid Parentheses
    // 建立stack,存放左括號下標,遇到右括號則依次出棧
    int longestValidParentheses(string s) {
        vector<int> vec(s.size(),0);
        stack<int> Stack;   //存下標
        for(int i = 0; i < s.size(); i++){
            if( s[i] == '(' ){   //左括號下標進棧
                Stack.push(i);
            }
            else{
                if(Stack.empty()) continue;  // 棧爲空,則說明前面無對應左括號,跳過即可
                else{
                    if(Stack.top()>0 && s[Stack.top()-1]==')'){
                        vec[i] = i - Stack.top() + 1 + vec[Stack.top()-1];    //類似"()()"的情況,左括號前面是右括號,需要加上已匹配的括號對
                    }
                    else{
                        vec[i] = i - Stack.top() + 1;  //否則直接計算下標差值 "()" "((()))"
                    }
                    Stack.pop();  //出棧
                }
            }
            
        }
        int maxPair = 0;
        for(int i = 0; i < s.size(); i++){
            if(vec[i] > maxPair) maxPair = vec[i];
        }
        return maxPair;
    }
};


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