Skip to content

Commit

Permalink
refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
JasonGitHub committed Dec 20, 2013
1 parent fc61eb3 commit 9493f94
Showing 1 changed file with 10 additions and 12 deletions.
22 changes: 10 additions & 12 deletions C++/chapStackAndQueue.tex
Original file line number Diff line number Diff line change
Expand Up @@ -104,28 +104,26 @@ \subsubsection{使用栈}
\subsubsection{Dynamic Programming, One Pass}
\begin{Code}
// LeetCode, Longest Valid Parenthese
// 时间复杂度O(n),空间复杂度O(1)
// @author 一只杰森(http://weibo.com/2197839961)
// 时间复杂度O(n),空间复杂度O(n)
// @author 一只杰森(http://weibo.com/wjson)
class Solution {
public:
int longestValidParentheses(string s) {
if (s.empty()) return 0;
int ret = 0;
int* d = new int[s.size()];
d[s.size() - 1] = 0;
int ret = 0;
for (int i = s.size() - 2; i >= 0; --i) {
if (s[i] == ')') d[i] = 0;
else {
int match = i + d[i + 1] + 1; // case: "((...))"
if (match < s.size() && s[match] == ')') { // found matching ')'
d[i] = match - i + 1;
if (match + 1 < s.size()) d[i] += d[match + 1]; // more valid sequence after j: "((...))(...)"
} else {
d[i] = 0; // no matching ')'
}
int match = i + d[i + 1] + 1;
if (s[i] == '(' && match < s.size() && s[match] == ')') {
d[i] = d[i + 1] + 2;
if (match + 1 < s.size()) d[i] += d[match + 1];
} else {
d[i] = 0;
}
ret = max(ret, d[i]);
}
delete[] d;
return ret;
}
};
Expand Down

0 comments on commit 9493f94

Please sign in to comment.