您的位置:首页 > 其它

[Leetcode] Longest Valid Parentheses

2014-04-01 01:06 288 查看
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)。

class Solution {
public:
int longestValidParentheses(string s) {
bool *a = new bool[s.length()];
memset(a, false, s.length());
stack<int> st;
for (int i = 0; i < s.length(); ++i) {
if (s[i] == '(') {
st.push(i);
} else if (s[i] == ')' && !st.empty()) {
a[i] = true;
a[st.top()] = true;
st.pop();
}
}
int max_len = 0, cur_len = 0;
for (int i = 0; i < s.length(); ++i) {
if (a[i]) ++cur_len;
else cur_len = 0;
max_len = max(max_len, cur_len);
}
return max_len;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: