8000 refactor · learningpro/leetcode@9493f94 · GitHub
[go: up one dir, main page]

Skip to content

Commit 9493f94

Browse files
committed
refactor
1 parent fc61eb3 commit 9493f94

File tree

1 file changed

+10
-12
lines changed

1 file changed

+10
-12
lines changed

C++/chapStackAndQueue.tex

+10-12
Original file line numberDiff line numberDiff line change
@@ -104,28 +104,26 @@ \subsubsection{使用栈}
104104
\subsubsection{Dynamic Programming, One Pass}
105105
\begin{Code}
106106
// LeetCode, Longest Valid Parenthese
107-
// 时间复杂度O(n),空间复杂度O(1)
108-
// @author 一只杰森(http://weibo.com/2197839961)
107+
// 时间复杂度O(n),空间复杂度O(n)
108+
// @author 一只杰森(http://weibo.com/wjson)
109109
class Solution {
110110
public:
111111
int longestValidParentheses(string s) {
112112
if (s.empty()) return 0;
113-
int ret = 0;
114113
int* d = new int[s.size()];
115114
d[s.size() - 1] = 0;
115+
int ret = 0;
116116
for (int i = s.size() - 2; i >= 0; --i) {
117-
if (s[i] == ')') d[i] = 0;
118-
else {
119-
int match = i + d[i + 1] + 1; // case: "((...))"
120-
if (match < s.size() && s[match] == ')') { // found matching ')'
121-
d[i] = match - i + 1;
122-
if (match + 1 < s.size()) d[i] += d[match + 1]; // more valid sequence after j: "((...))(...)"
123-
} else {
124-
d[i] = 0; // no matching ')'
125-
}
117+
int match = i + d[i + 1] + 1;
118+
if (s[i] == '(' && match < s.size() && s[match] == ')') {
119+
d[i] = d[i + 1] + 2;
120+
if (match + 1 < s.size()) d[i] += d[match + 1];
121+
} else {
122+
d[i] = 0;
126123
}
127124
ret = max(ret, d[i]);
128125
}
126+
delete[] d;
129127
return ret;
130128
}
131129
};

0 commit comments

Comments
 (0)
0