8000 Merge pull request #5 from JasonGitHub/master · www2620552/leetcode@78a9ed9 · GitHub
[go: up one dir, main page]

Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 78a9ed9

Browse files
committed
Merge pull request soulmachine#5 from JasonGitHub/master
Added DP solution for "Longest Valid Parenthese"
2 parents f68d5ce + fc61eb3 commit 78a9ed9

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

C++/chapStackAndQueue.tex

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,36 @@ \subsubsection{使用栈}
101101
};
102102
\end{Code}
103103

104+
\subsubsection{Dynamic Programming, One Pass}
105+
\begin{Code}
106+
// LeetCode, Longest Valid Parenthese
107+
// 时间复杂度O(n),空间复杂度O(1)
108+
// @author 一只杰森(http://weibo.com/2197839961)
109+
class Solution {
110+
public:
111+
int longestValidParentheses(string s) {
112+
if (s.empty()) return 0;
113+
int ret = 0;
114+
int* d = new int[s.size()];
115+
d[s.size() - 1] = 0;
116+
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: "((...)) 846C (...)"
123+
} else {
124+
d[i] = 0; // no matching ')'
125+
}
126+
}
127+
ret = max(ret, d[i]);
128+
}
129+
return ret;
130+
}
131+
};
132+
\end{Code}
133+
104134

105135
\subsubsection{两遍扫描}
106136
\begin{Code}

0 commit comments

Comments
 (0)
0