1. 程式人生 > >LeetCode 32 — Longest Valid Parentheses(最長有效括號)

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 “()()”

翻譯
給定一個只包含 ‘(’ 和 ‘)’ 的字串,找出最長的包含有效括號的子串的長度。

示例 1:
輸入: "(()"
輸出: 2
解釋: 最長有效括號子串為 “()”

示例 2:
輸入: ")()())"
輸出: 4
解釋: 最長有效括號子串為 “()()”

分析
很久之前寫的解法了,複雜度為O(n^2),由於資料量不大勉強過了。正確做法還是應該用棧或者動態規劃。

c++實現

class Solution {
public:
    int longestValidParentheses(string s) {
        int res = 0;
        bool found =
false; for (int i = 0; i < s.length(); i++) { int length = 0; int tmp = 0; int start = i; for (int j = i; j < s.length(); j++) { if (s[j] == '(') tmp++; else tmp--
; if (tmp == 0) { length += j+1-start; start = j+1; if (res < length) res = length; } if (tmp < 0) { length = 0; start = j+1; tmp = 0; } } } return res; } };