File tree Expand file tree Collapse file tree 2 files changed +45
-1
lines changed Expand file tree Collapse file tree 2 files changed +45
-1
lines changed Original file line number Diff line number Diff line change @@ -68,7 +68,7 @@ \subsubsection{分析}
68
68
无
69
69
70
70
71
- \subsubsection {代码 }
71
+ \subsubsection {使用栈 }
72
72
\begin {Code }
73
73
// LeetCode, Longest Valid Parenthese
74
74
// 使用栈,时间复杂度O(n),空间复杂度O(n)
@@ -102,6 +102,50 @@ \subsubsection{代码}
102
102
\end {Code }
103
103
104
104
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
+
105
149
\subsubsection {相关题目 }
106
150
\begindot
107
151
\item Valid Parentheses, 见 \S \ref {sec:valid-parentheses }
You can’t perform that action at this time.
0 commit comments