LeetCode實(shí)戰(zhàn):最長(zhǎng)有效括號(hào)

題目英文

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

<b>Example 1</b>:

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

<b>Example 2</b>:

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

題目中文

給定一個(gè)只包含 '(' 和 ')' 的字符串,找出最長(zhǎng)的包含有效括號(hào)的子串的長(zhǎng)度。

<b>示例 1</b>:

輸入: "(()"
輸出: 2
解釋: 最長(zhǎng)有效括號(hào)子串為 "()"

<b>示例 2</b>:

輸入: ")()())"
輸出: 4
解釋: 最長(zhǎng)有效括號(hào)子串為 "()()"

<b>示例 3</b>:

輸入: ""
輸出: 0
解釋: 

<b>示例 4</b>:

輸入: "()(())"
輸出: 6
解釋: 最長(zhǎng)有效括號(hào)子串為 "()(())"

算法實(shí)現(xiàn)

我們可以用棧在遍歷給定字符串的過(guò)程中去判斷到目前為止掃描的子字符串的有效性,同時(shí)計(jì)算最長(zhǎng)有效字符串的長(zhǎng)度。我們首先將 ?1 放入棧頂。

  • 對(duì)于遇到的每個(gè)‘(’,我們將它的下標(biāo)放入棧中。
  • 對(duì)于遇到的每個(gè)‘)’,我們彈出棧頂?shù)脑?,判斷有效性,?jì)算有效長(zhǎng)度。
public class Solution {
    public int LongestValidParentheses(string s) {
        Stack<int> stack = new Stack<int>();
        stack.Push(-1);
        int result = 0;
        for (int i = 0; i < s.Length; i++)
        {
            if (s[i] == '(')
            {
                stack.Push(i);
            }
            else
            {
                stack.Pop();
                if (stack.Count == 0)
                {
                    stack.Push(i);
                }
                else
                {
                    result = Math.Max(result, i - stack.First());
                }
            }
        }
        return result;
    }
}

實(shí)驗(yàn)結(jié)果

  • 狀態(tài):通過(guò)
  • 230 / 230 個(gè)通過(guò)測(cè)試用例
  • 執(zhí)行用時(shí):104 ms
提交結(jié)果

相關(guān)圖文

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容