1. 程式人生 > >LeetCode-32-Longest Valid Parentheses

LeetCode-32-Longest Valid Parentheses

str lan form 棧模擬 ret amp pan 計算 urn

算法描述:

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

解題思路:用棧模擬,遇到左括號進棧,右括號出棧,並計算合法括號數量。

    int longestValidParentheses(string s) {
        stack<int> stk;
        int res = 0;
        int i = 0;
        int start = -1;
        while(i < s.size()){
            if(s[i]==(){
                stk.push(i);
            }else{
                if(stk.empty())
                    start 
= i; else{ stk.pop(); if(stk.empty()) res = max(res, i- start); else res = max(res, i-stk.top()); } } i++; } return res; }

LeetCode-32-Longest Valid Parentheses