[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 };

 

posted @ 2014-04-01 01:06  Eason Liu  阅读(3939)  评论(1编辑  收藏  举报