Skip to content

Commit 3b53a40

Browse files
committed
Longest Valid Parentheses @曹鹏 的解法
1 parent 33526ac commit 3b53a40

File tree

2 files changed

+45
-1
lines changed

2 files changed

+45
-1
lines changed

C++/LeetCodet题解(C++版).pdf

2.17 KB
Binary file not shown.

C++/chapStackAndQueue.tex

Lines changed: 45 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ \subsubsection{分析}
6868
6969

7070

71-
\subsubsection{代码}
71+
\subsubsection{使用栈}
7272
\begin{Code}
7373
// LeetCode, Longest Valid Parenthese
7474
// 使用栈,时间复杂度O(n),空间复杂度O(n)
@@ -102,6 +102,50 @@ \subsubsection{代码}
102102
\end{Code}
103103

104104

105+
\subsubsection{两遍扫描}
106+
\begin{Code}
107+
// LeetCode, Longest Valid Parenthese
108+
// 两遍扫描,时间复杂度O(n),空间复杂度O(1)
109+
// @author 曹鹏(http://weibo.com/cpcs)
110+
class Solution {
111+
public:
112+
int longestValidParentheses(string s) {
113+
int answer = 0, depth = 0, start = -1;
114+
for (int i = 0; i < s.size(); ++i) {
115+
if (s[i] == '(') {
116+
++depth;
117+
} else {
118+
--depth;
119+
if (depth < 0) {
120+
start = i;
121+
depth = 0;
122+
} else if (depth == 0) {
123+
answer = max(answer, i - start);
124+
}
125+
}
126+
}
127+
128+
depth = 0;
129+
start = s.size();
130+
for (int i = s.size() - 1; i >= 0; --i) {
131+
if (s[i] == ')') {
132+
++depth;
133+
} else {
134+
--depth;
135+
if (depth < 0) {
136+
start = i;
137+
depth = 0;
138+
} else if (depth == 0) {
139+
answer = max(answer, start - i);
140+
}
141+
}
142+
}
143+
return answer;
144+
}
145+
};
146+
\end{Code}
147+
148+
105149
\subsubsection{相关题目}
106150
\begindot
107151
\item Valid Parentheses, 见 \S \ref{sec:valid-parentheses}

0 commit comments

Comments
 (0)