[Leetcode] 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.

 

很多人會說這道題用動規,可是用動規每次匹配后還要向前到上一個匹配跟這個匹配是否連接,時間復雜度為O(n^2),其實可以換個想法,用一個bool數組來標記已經匹配過的字符,找到最長的連續標記的長度就是所求的結果。只要遍歷兩遍數組,時間復雜度為O(n)。

 1 class Solution {
 2 public:
 3     int longestValidParentheses(string s) {
 4         bool *a = new bool[s.length()];
 5         memset(a, false, s.length());
 6         stack<int> st;
 7         for (int i = 0; i < s.length(); ++i) {
 8             if (s[i] == '(') {
 9                 st.push(i);
10             } else if (s[i] == ')' && !st.empty()) {
11                 a[i] = true;
12                 a[st.top()] = true;
13                 st.pop();
14             }
15         }
16         int max_len = 0, cur_len = 0;
17         for (int i = 0; i < s.length(); ++i) {
18             if (a[i]) ++cur_len;
19             else cur_len = 0;
20             max_len = max(max_len, cur_len);
21         }
22         return max_len;
23     }
24 };

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM