Skip to content

Commit 4e81197

Browse files
committed
Refactored Longest Valid Parentheses
1 parent 9493f94 commit 4e81197

File tree

1 file changed

+7
-10
lines changed

1 file changed

+7
-10
lines changed

C++/chapStackAndQueue.tex

+7-10
Original file line numberDiff line numberDiff line change
@@ -109,21 +109,18 @@ \subsubsection{Dynamic Programming, One Pass}
109109
class Solution {
110110
public:
111111
int longestValidParentheses(string s) {
112-
if (s.empty()) return 0;
113-
int* d = new int[s.size()];
114-
d[s.size() - 1] = 0;
112+
vector<int> f(s.size(), 0);
115113
int ret = 0;
116114
for (int i = s.size() - 2; i >= 0; --i) {
117-
int match = i + d[i + 1] + 1;
115+
int match = i + f[i + 1] + 1;
116+
// case: "((...))"
118117
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;
118+
f[i] = f[i + 1] + 2;
119+
// if a valid sequence exist afterwards "((...))()"
120+
if (match + 1 < s.size()) f[i] += f[match + 1];
123121
}
124-
ret = max(ret, d[i]);
122+
ret = max(ret, f[i]);
125123
}
126-
delete[] d;
127124
return ret;
128125
}
129126
};

0 commit comments

Comments
 (0)